Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert []byte to *bytes.Buffer

Tags:

go

gob

I am trying to decode a gob output that I am sending through another fasthttp endpoint and receiving an error Fasthttp endpoint(encode []string through gob) ----> Fasthttp endpoint( receive and decode)

buffer := &bytes.Buffer{}
buffer  = ctx.PostBody()
backToStringSlice := []string{}  
gob.NewDecoder(buffer).Decode(&backToStringSlice)

I am getting error: ctx.PostBody() (type []byte) as type *bytes.Buffer in assignment

how do I convert []byte to *bytes.Buffer.

Any help is appreciated.

like image 383
rithik r Avatar asked Oct 12 '18 07:10

rithik r


People also ask

What is a buffer of bytes?

Like a byte is a group of 8 bits, a buffer is a group of a pre-defined number of bytes. If we have a group of 3 bytes, this could either represent 3 values between 0 and 255, but also one single value between 0 and 16777216 (2563).

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 the difference between ByteBuffer and byte array?

There are several differences between a byte array and ByteBuffer class in Java, but the most important of them is that bytes from byte array always reside in Java heap space, but bytes in a ByteBuffer may potentially reside outside of the Java heap in case of direct byte buffer and memory mapped files.

What is Golang buffer?

In go language, the buffer belongs to the byte package of the Go language, and we can use these package to manipulate the byte of the string. For example, suppose we have a string. We can read the length of the string with the len function, which will return the numeric length, but what if the strings are too large.


1 Answers

NewBuffer will do what you want

package main

import (
    "fmt"
    "bytes"
)

func main() {
        foo:=[]byte{65,66,67}
        z:=bytes.NewBuffer(foo)
    fmt.Println("Hello, playground", foo, z)
}
like image 117
Vorsprung Avatar answered Sep 30 '22 06:09

Vorsprung