dpj96988 2015-03-24 16:01
浏览 560
已采纳

如何转换(类型* bytes.Buffer)以用作w.Write参数中的[] byte

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)
  • 写回答

2条回答 默认 最新

  • doubiaokai4998 2015-03-24 16:13
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失