我正在尝试从服务器返回一些 json,但使用以下代码收到此错误
cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write
通过一点谷歌搜索,我找到了这个 SO 答案,但无法使其正常工作(请参阅带有错误消息的第二个代码示例)
第一个代码示例
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)
汪汪一只猫
相关分类