我试图从服务器返回一些 json 但使用以下代码收到此错误
cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write
通过一点谷歌搜索,我发现这个答案 https://stackoverflow.com/questions/23454940/getting-bytes-buffer-does-not-implement-io-writer-error-message但无法让它工作(请参阅带有错误消息的第二个代码示例)
第一个代码示例
buffer := new(bytes.Buffer)
for _, jsonRawMessage := range sliceOfJsonRawMessages{
if err := json.Compact(buffer, jsonRawMessage); err != nil{
fmt.Println("error")
}
}
fmt.Println("json returned", buffer)//this is json
w.Header().Set("Content-Type", contentTypeJSON)
w.Write(buffer)//error: cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write
第二个代码示例有错误
cannot use foo (type *bufio.Writer) as type *bytes.Buffer in argument to json.Compact
cannot use foo (type *bufio.Writer) as type []byte in argument to w.Write
var b bytes.Buffer
foo := bufio.NewWriter(&b)
for _, d := range t.J{
if err := json.Compact(foo, d); err != nil{
fmt.Println("error")
}
}
w.Header().Set("Content-Type", contentTypeJSON)
w.Write(foo)
写入需要一个[]byte
(字节切片),并且您有一个*bytes.Buffer
(指向缓冲区的指针)。
您可以使用以下命令从缓冲区获取数据Buffer.Bytes() http://golang.org/pkg/bytes/#Buffer.Bytes并将其交给Write()
:
_, err = w.Write(buffer.Bytes())
...或使用Buffer.WriteTo() http://golang.org/pkg/bytes/#Buffer.WriteTo将缓冲区内容直接复制到Writer
:
_, err = buffer.WriteTo(w)
Using a bytes.Buffer
并不是绝对必要的。json.Marshal() http://golang.org/pkg/encoding/json/#Marshal返回一个[]byte
直接地:
var buf []byte
buf, err = json.Marshal(thing)
_, err = w.Write(buf)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)