【问题标题】:json.Marshal how body of http.newRequesthttp.newRequest 的 json.Marshal 正文如何
【发布时间】:2014-09-30 02:01:51
【问题描述】:

我正在创建一个用于管理 DigitalOcean Droplets 的小控制台,但出现此错误:

不能在 http.NewRequest 的参数中使用 s(类型 []byte)作为类型 io.Reader: []byte 没有实现 io.Reader(缺少 Read 方法)

如何将 s []bytes 转换为 func NewRequest 的良好值类型?! NewRequest 期望 Body 类型为 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)

【问题讨论】:

标签: json go type-conversion


【解决方案1】:

正如@elithrar 所说,使用bytes.NewBuffer

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

这将从[]bytes 创建一个*bytes.Buffer。而bytes.Buffer 实现了http.NewRequest 所需的io.Reader 接口。

【讨论】:

    【解决方案2】:

    由于您是从某个对象开始的,因此您可以使用 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

    【讨论】:

      【解决方案3】:

      使用bytes.NewReader[]byte 创建一个io.Reader

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

      【讨论】:

        猜你喜欢
        • 2022-08-17
        • 2022-12-02
        • 2017-12-24
        • 2014-12-07
        • 1970-01-01
        • 2021-01-02
        • 1970-01-01
        • 2021-12-21
        相关资源
        最近更新 更多