Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode a base64 request body into a binary

Tags:

go

I'm fairly new to the Go language and having a hard time achieving the following: I'm receiving a base64 string (basically, an encoded image) and need to transform it to the 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 is not working, because DecodeString expects a string... how do I transform request.Body into a string? Any tips are very much appreciated!

like image 921
Ralf Avatar asked Mar 19 '23 22:03

Ralf


1 Answers

Do not use base64.StdEncoding.DecodeString, instead set up a decoder directly from the r.Body

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

now use dec, e.g. dump to a bytes.Buffer like

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

which will decode r.Body into buf or copy directly to a http.Response or a file.

Or use Peter's method below if keeping all in memory is okay.

like image 105
Volker Avatar answered Mar 28 '23 09:03

Volker