如何将(type *bytes.Buffer)转换为[]byte以在w.Write的参数中使用

60

我试图从服务器返回一些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)
2个回答

76

在这里,Write()需要一个[]byte(字节片),而你有一个*bytes.Buffer(指向一个缓冲区的指针)。

你可以使用Buffer.Bytes()从缓冲区中获取数据,并将其传递给Write()

_, err = w.Write(buffer.Bytes())

...或者使用Buffer.WriteTo()将缓冲区内容直接复制到Writer中:

_, err = buffer.WriteTo(w)

使用 bytes.Buffer 并非必须。 json.Marshal() 直接返回一个 []byte

var buf []byte

buf, err = json.Marshal(thing)

_, err = w.Write(buf)

谢谢,但我需要一点澄清。在这种情况下,我应该传递什么给json.Compact(我需要使用它来删除\n和\t)?您能否针对我的代码示例提供更多具体信息?如果您能帮忙,谢谢。 - Leahcim
例如,这将字节打印到我的终端- fmt.Println("json returned", buffer.Bytes()),如果我将buffer.Bytes()传递给w.Write,它也会返回一串字节流。我需要返回JSON。请注意,我无法测试此功能,因为我的浏览器存在其他问题。 - Leahcim
@Leahcim 如果你想打印它,尝试使用 buffer.String()buffer.Bytes() 返回 JSON 文本的 UTF-8 编码字节。 - icza

10

这是我解决问题的方法

readBuf, _ := ioutil.ReadAll(jsonStoredInBuffVariable)

这段代码将从缓冲变量中读取并输出[]byte值。


2
Buffer.Bytes() 对你不起作用吗?它似乎是最简单的方法。 - chicks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接