Encode base64 request body to binary

I am new to Go and can hardly achieve the following: I get a base64 string (basically an encoded image) and must convert it to binary form on the server.

func addOrUpdateUserBase64(w http.ResponseWriter, r *http.Request, params martini.Params) {
    c := appengine.NewContext(r)
    sDec, _ := b64.StdEncoding.DecodeString(r.Body)
...

This does not work because DecodeString expects a string ... how to convert request.Body to a string? Any advice is greatly appreciated!

+4
source share
3 answers

Do not use base64.StdEncoding.DecodeString, instead, configure the decoder directly fromr.Body

dec := base64.NewDecoder(base64.StdEncoding, r.Body)`  // dec is an io.Reader

now use decfor example. dump to bytes.Bufferhow

buf := &bytes.Buffer{}
n, err := io.copy(buf, dec)

which will decode r.Bodyin buf or copy directly to http.Response or the file.

Or use the Peter method below if you keep everything in memory in order.

+6

func (* Encoding)

func (enc *Encoding) Decode(dst, src []byte) (n int, err error)

src, enc. DecodedLen (len (src)) dst . src base64, CorruptInputError. (\ r \n) .

+1

And another option is to just give r.Body:

// Edit, fix the code for working with io.Reader

import "io/ioutil"
..........
if body, err := ioutil.ReadAll(r.Body); err == nil {
       sDec, _ := b64.StdEncoding.DecodeString(string(body))
}
-1
source

Source: https://habr.com/ru/post/1536099/


All Articles