Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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)
like image 594
Leahcim Avatar asked Mar 24 '15 16:03

Leahcim


People also ask

What is [] byte Golang?

The byte type in Golang is an alias for the unsigned integer 8 type ( uint8 ). The byte type is only used to semantically distinguish between an unsigned integer 8 and a byte. The range of a byte is 0 to 255 (same as uint8 ).

How do I create a byte buffer in Golang?

To create a byte in Go, assign an ASCII character to a variable. A byte in Golang is an unsigned 8-bit integer. The byte type represents ASCII characters, while the rune data type represents a broader set of Unicode characters encoded in UTF-8 format.

What is byte slice?

Byte slices are a list of bytes that represent UTF-8 encodings of Unicode code points. Taking the information from above, we could create a byte slice that represents the word “Go”: bs := []byte{71, 111}


2 Answers

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) 
like image 153
lnmx Avatar answered Sep 21 '22 01:09

lnmx


This is how I solved my problem

readBuf, _ := ioutil.ReadAll(jsonStoredInBuffVariable)

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

like image 27
Joyston Avatar answered Sep 25 '22 01:09

Joyston