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)
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With