我正在嘗試從服務器返回一些 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 jsonw.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.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貢獻1898條經驗 獲得超8個贊
Write 需要一個[]byte(字節片),并且您有一個*bytes.Buffer(指向緩沖區的指針)。
您可以使用Buffer.Bytes()從緩沖區獲取數據并將其提供給Write():
_, err = w.Write(buffer.Bytes())
...或使用Buffer.WriteTo()將緩沖區內容直接復制到 a Writer:
_, err = buffer.WriteTo(w)
使用 abytes.Buffer并不是絕對必要的。 json.Marshal()[]byte直接返回一個:
var buf []byte
buf, err = json.Marshal(thing)
_, err = w.Write(buf)
- 2 回答
- 0 關注
- 515 瀏覽
添加回答
舉報
0/150
提交
取消