Go 如何将(type*bytes.Buffer)转换为用作参数中的[]字节,并将其转换为w.Write
我试图从服务器返回一些json,但通过以下代码得到了这个错误Go 如何将(type*bytes.Buffer)转换为用作参数中的[]字节,并将其转换为w.Write,go,Go,我试图从服务器返回一些json,但通过以下代码得到了这个错误 cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write 通过一点谷歌搜索,我找到了,但无法让它工作(请参阅第二个代码示例,其中包含错误消息) 第一个代码示例 buffer := new(bytes.Buffer) for _, jsonRawMessage := range sliceOfJsonRawMessages{ if
cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write
通过一点谷歌搜索,我找到了,但无法让它工作(请参阅第二个代码示例,其中包含错误消息)
第一个代码示例
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)
写入需要一个
[]字节(字节片),而您有一个*字节.Buffer
(指向缓冲区的指针)
您可以使用从缓冲区获取数据,并将其交给Write()
:
…或用于将缓冲区内容直接复制到写入程序
:
_, err = buffer.WriteTo(w)
严格来说,不需要使用字节缓冲区。直接返回[]字节
:
var buf []byte
buf, err = json.Marshal(thing)
_, err = w.Write(buf)
这就是我解决问题的方法
readBuf, _ := ioutil.ReadAll(jsonStoredInBuffVariable)
此代码将从缓冲区变量读取并输出[]字节值谢谢,但我需要一些澄清。在这种情况下(我需要使用它来删除\n和\t),我将传递什么给json.Compact?你能提供更多关于我的代码示例的信息吗?谢谢您的帮助。例如,这会将字节打印到我的终端-fmt.Println(“json返回”,buffer.bytes())
,如果我将buffer.bytes()传递给w.Write,它不会也返回字节流吗。我需要你归还我。注意,我无法测试它,因为我的浏览器还有其他问题。@Leahcim如果要打印它,请尝试buffer.String()
buffer.Bytes()
返回json文本的UTF-8编码字节。
readBuf, _ := ioutil.ReadAll(jsonStoredInBuffVariable)