如何将`(type *bytes.Buffer)`转换为作为`w.Write`参数的`[]byte`?

huangapple go评论84阅读模式
英文:

How to convert (type *bytes.Buffer) to use as []byte in argument to w.Write

问题

我正在尝试从服务器返回一些 JSON,但是在以下代码中遇到了这个错误:

cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write

通过一些搜索,我找到了这个 Stack Overflow 的答案,但是无法使其工作(请参考带有错误信息的第二段代码示例)。

第一个代码示例:

buffer := new(bytes.Buffer)

for _, jsonRawMessage := range sliceOfJsonRawMessages {
    if err := json.Compact(buffer, jsonRawMessage); err != nil {
        fmt.Println("error")
    }
}

fmt.Println("json returned", buffer) // 这是 JSON
w.Header().Set("Content-Type", contentTypeJSON)

w.Write(buffer) // 错误: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)
英文:

I'm trying to return some json back from the server but get this error with the following code

cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write

With a little googling, I found this SO answer but couldn't get it to work (see second code sample with error message)

1st code sample

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

2nd code sample with error

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)

答案1

得分: 75

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)
英文:

Write requires a []byte (slice of bytes), and you have a *bytes.Buffer (pointer to a buffer).

You could get the data from the buffer with Buffer.Bytes() and give that to Write():

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

...or use Buffer.WriteTo() to copy the buffer contents directly to a Writer:

_, err = buffer.WriteTo(w)

Using a bytes.Buffer is not strictly necessary. json.Marshal() returns a []byte directly:

var buf []byte

buf, err = json.Marshal(thing)

_, err = w.Write(buf)

答案2

得分: 10

这是我解决问题的方法:

readBuf, _ := ioutil.ReadAll(jsonStoredInBuffVariable)

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

英文:

This is how I solved my problem

readBuf, _ := ioutil.ReadAll(jsonStoredInBuffVariable)

This code will read from the buffer variable and output []byte value

huangapple
  • 本文由 发表于 2015年3月25日 00:01:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/29237411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定