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

时间:2015-03-24 16:01:40

标签: go

我试图从服务器返回一些json但是使用以下代码获取此错误

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

通过一点点Google搜索,我发现this SO answer但无法使其正常工作(请参阅第二个代码示例并显示错误消息)

第一个代码示例

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

错误的第二个代码示例

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 个答案:

答案 0 :(得分:33)

写入需要[]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)

答案 1 :(得分:2)

这就是我解决问题的方法

   struct User {
    var userName: String
    var email: String
    var age: Int
    static var currentUser = User(userName: "Bob", email: "bob@gmail.com", age: 18) //This line was typed by me.
    // My answer for the 2nd part.
    mutating func logIn(user: User) {
        User.currentUser = user
        print("\(userName) has logged in.")
    }
}

此代码将从缓冲区变量和输出[]字节值

中读取