如何转换(键入*bytes.Buffer)以在w.Write的参数中用作[]字节

Lea*_*cim 30 go

我试图从服务器返回一些json,但使用以下代码得到此错误

cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write
Run Code Online (Sandbox Code Playgroud)

通过一点谷歌搜索,我发现这个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
Run Code Online (Sandbox Code Playgroud)

第二个代码示例有错误

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)
Run Code Online (Sandbox Code Playgroud)

lnm*_*nmx 40

写需要一个[]byte(切片的字节),并且你有一个*bytes.Buffer(指向缓冲区的指针).

您可以使用Buffer.Bytes()从缓冲区获取数据并将其提供给Write():

_, err = w.Write(buffer.Bytes())
Run Code Online (Sandbox Code Playgroud)

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

_, err = buffer.WriteTo(w)
Run Code Online (Sandbox Code Playgroud)

使用a bytes.Buffer并非绝对必要. json.Marshal()[]byte直接返回:

var buf []byte

buf, err = json.Marshal(thing)

_, err = w.Write(buf)
Run Code Online (Sandbox Code Playgroud)


Joy*_*ton 7

这就是我解决我的问题的方法

readBuf, _ := ioutil.ReadAll(jsonStoredInBuffVariable)
Run Code Online (Sandbox Code Playgroud)

此代码将从缓冲区变量中读取并输出 []byte 值

  • `Buffer.Bytes()` 不适合你吗?这似乎是最简单的方法。 (2认同)