Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.Marshal how body of http.newRequest

I'm working to create a little console for managing DigitalOcean Droplets, and I have this error:

cannot use s (type []byte) as type io.Reader in argument to http.NewRequest: []byte does not implement io.Reader (missing Read method)

How can I convert s []bytes in a good type of value for func NewRequest?! NewRequest expects Body of type io.Reader..

s, _ := json.Marshal(r);

// convert type

req, _ := http.NewRequest("GET", "https://api.digitalocean.com/v2/droplets", s)                                          
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))                                                          
req.Header.Set("Content-Type", "application/json")                            
response, _ := client.Do(req)
like image 200
GianArb Avatar asked Aug 06 '14 23:08

GianArb


People also ask

How do you read request body in Go?

In Go, you can use the io. ReadAll() function (or ioutil. ReadAll() in Go 1.15 and earlier) to read the whole body into a slice of bytes and convert the byte slice to a string with the string() function. To exclude the response body from the output, change the boolean argument to httputil.

How do I get Golang body data?

One option is to read the whole body using ioutil. ReadAll() , which gives you the body as a byte slice. You may use bytes. NewBuffer() to obtain an io.

How do I send a JSON string in a post request in Go?

The JavaScript Object Notation (JSON) is a commonly used data transmission format in web development. It is simple to use and understand. You can create a JSON POST request with the Go language, but you need to import several Go packages.

What is marshal in JSON?

Go's terminology calls marshal the process of generating a JSON string from a data structure, and unmarshal the act of parsing JSON to a data structure.


1 Answers

As @elithrar says use bytes.NewBuffer

b := bytes.NewBuffer(s)
http.NewRequest(..., b) 

That will create a *bytes.Buffer from []bytes. and bytes.Buffer implements the io.Reader interface that http.NewRequest requires.

like image 120
fabrizioM Avatar answered Oct 16 '22 20:10

fabrizioM