我正在嘗試從服務(wù)器返回一些 json,但使用以下代碼收到此錯(cuò)誤cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write通過(guò)一點(diǎn)谷歌搜索,我找到了這個(gè) SO 答案,但無(wú)法使其正常工作(請(qǐng)參閱帶有錯(cuò)誤消息的第二個(gè)代碼示例)第一個(gè)代碼示例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 jsonw.Header().Set("Content-Type", contentTypeJSON)w.Write(buffer)//error: cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write有錯(cuò)誤的第二個(gè)代碼示例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.Writevar b bytes.Bufferfoo := 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 回答

汪汪一只貓
TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
Write 需要一個(gè)[]byte(字節(jié)片),并且您有一個(gè)*bytes.Buffer(指向緩沖區(qū)的指針)。
您可以使用Buffer.Bytes()從緩沖區(qū)獲取數(shù)據(jù)并將其提供給Write():
_, err = w.Write(buffer.Bytes())
...或使用Buffer.WriteTo()將緩沖區(qū)內(nèi)容直接復(fù)制到 a Writer:
_, err = buffer.WriteTo(w)
使用 abytes.Buffer并不是絕對(duì)必要的。 json.Marshal()[]byte直接返回一個(gè):
var buf []byte
buf, err = json.Marshal(thing)
_, err = w.Write(buf)
- 2 回答
- 0 關(guān)注
- 517 瀏覽
添加回答
舉報(bào)
0/150
提交
取消