英文:
json.Marshal how body of http.newRequest
问题
我正在努力创建一个用于管理DigitalOcean Droplets的小型控制台,但是我遇到了这个错误:
无法将s(类型为[]byte)作为http.NewRequest的参数类型io.Reader使用:
[]byte没有实现io.Reader(缺少Read方法)
我该如何将s []byte
转换为NewRequest
函数所需的正确类型的值?NewRequest
函数期望Body
参数的类型为io.Reader
。。
s, _ := json.Marshal(r);
// 进行类型转换
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)
英文:
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)
答案1
得分: 36
根据@elithrar的说法,使用bytes.NewBuffer
函数:
b := bytes.NewBuffer(s)
http.NewRequest(..., b)
这将从[]byte
创建一个*bytes.Buffer
,而bytes.Buffer
实现了http.NewRequest
所需的io.Reader
接口。
英文:
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.
答案2
得分: 3
由于您正在使用某个对象开始,您可以使用Encode
而不是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
英文:
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)
}
答案3
得分: 1
使用bytes.NewReader函数将[]byte
转换为io.Reader
。
s, _ := json.Marshal(r)
req, _ := http.NewRequest("GET",
"https://api.digitalocean.com/v2/droplets",
bytes.NewReader(s))
英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论