GianArb
GianArb

Reputation: 1694

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)

Upvotes: 17

Views: 28459

Answers (3)

Zombo
Zombo

Reputation: 1

Since you are starting with some object, you can just use Encode instead of Marshal:

package main

import (
   "bytes"
   "encoding/json"
   "net/http"
)

func main() {
   m, b := map[string]int{"month": 12}, new(bytes.Buffer)
   json.NewEncoder(b).Encode(m)
   r, e := http.NewRequest("GET", "https://stackoverflow.com", b)
   if e != nil {
      panic(e)
   }
   new(http.Client).Do(r)
}

https://golang.org/pkg/encoding/json#Encoder.Encode

Upvotes: 4

beckler
beckler

Reputation: 29

Use bytes.NewReader to create an io.Reader from a []byte.

s, _ := json.Marshal(r);
req, _ := http.NewRequest("GET",
   "https://api.digitalocean.com/v2/droplets",
   bytes.NewReader(s))                                          

Upvotes: 2

fabmilo
fabmilo

Reputation: 48330

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.

Upvotes: 36

Related Questions