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

前端 未结 2 1547
借酒劲吻你
借酒劲吻你 2021-01-31 07:56

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         


        
相关标签:
2条回答
  • 2021-01-31 08:31

    This is how I solved my problem

    readBuf, _ := ioutil.ReadAll(jsonStoredInBuffVariable)
    

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

    0 讨论(0)
  • 2021-01-31 08:47

    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)
    
    0 讨论(0)
提交回复
热议问题