英文:
Encode a base64 request body into a binary
问题
我对Go语言还比较新手,对于以下问题遇到了困难:我收到了一个base64字符串(实际上是一个编码后的图像),需要在服务器上将其转换为二进制形式。
func addOrUpdateUserBase64(w http.ResponseWriter, r *http.Request, params martini.Params) {
c := appengine.NewContext(r)
sDec, _ := b64.StdEncoding.DecodeString(r.Body)
...
这段代码无法正常工作,因为DecodeString函数需要一个字符串作为参数...我该如何将request.Body转换为字符串?非常感谢任何提示!
英文:
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!
答案1
得分: 7
不要使用base64.StdEncoding.DecodeString
,而是直接从r.Body
设置一个解码器。
dec := base64.NewDecoder(base64.StdEncoding, r.Body) // dec 是一个 io.Reader
现在使用dec
,例如将其转储到bytes.Buffer
中:
buf := &bytes.Buffer{}
n, err := io.Copy(buf, dec)
这将把r.Body
解码到buf
中,或者直接复制到http.Response
或文件中。
如果将所有内容都保存在内存中没有问题,也可以使用Peter的方法。
英文:
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.
答案2
得分: 1
func (enc *Encoding) Decode(dst, src []byte) (n int, err error)
Decode使用编码enc对src进行解码。它最多将DecodedLen(len(src))字节写入dst,并返回写入的字节数。如果src包含无效的base64数据,它将返回成功写入的字节数和CorruptInputError。换行符(\r和\n)将被忽略。
英文:
> func (*Encoding) Decode
>
> func (enc *Encoding) Decode(dst, src []byte) (n int, err error)
>
> Decode decodes src using the encoding enc. It writes at most
> DecodedLen(len(src)) bytes to dst and returns the number of bytes
> written. If src contains invalid base64 data, it will return the
> number of bytes successfully written and CorruptInputError. New line
> characters (\r and \n) are ignored.
答案3
得分: 0
另外一个选择是将 r.Body
强制转换为 string
:
// 编辑,修复代码以适用于 io.Reader
import "io/ioutil"
..........
if body, err := ioutil.ReadAll(r.Body); err == nil {
sDec, _ := b64.StdEncoding.DecodeString(string(body))
}
英文:
And one more option would be just casting r.Body
to a string
:
//Edit, fixed the code to work with an io.Reader
import "io/ioutil"
..........
if body, err := ioutil.ReadAll(r.Body); err == nil {
sDec, _ := b64.StdEncoding.DecodeString(string(body))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论