【问题标题】:How to replace variable struct in golang http.NewRequest POST with request body如何用请求正文替换golang http.NewRequest POST中的变量结构
【发布时间】:2022-08-17 18:10:01
【问题描述】:

我是 golang 的新手,在使用请求正文修改数据结构时遇到问题,在此代码中我想从请求正文修改 var To 基于值,该怎么做? 这里是示例代码https://go.dev/play/p/25GaCvJo84I

正文:{\"phone\": \"1989876787\"}

type Payload struct {
    MessagingProduct string   `json:\"messaging_product\"`
    To               string   `json:\"to\"`
}

func send(c *gin.Context) {
    url := os.Getenv(\"URL\")
    accessToken := os.Getenv(\"ACCESS_TOKEN\")
    jsonData, err := ioutil.ReadAll(c.Request.Body)
    if err != nil {
        // Handle error
    }
    fmt.Println(\"payload\", string(jsonData))
    data := Payload{
        MessagingProduct: \"whatsapp\",
        To:        \"\", // how to replace this with request body
    }
    jsonStr, _ := json.Marshal(data)
    req, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonStr))
    req.Header.Set(\"Authorization\", \"Bearer \"+accessToken)
    req.Header.Set(\"Content-Type\", \"application/json\")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
}

    标签: go


    【解决方案1】:

    使用 gin 框架,可以使用绑定功能。

    type Payload struct {
        MessagingProduct string   `json:"messaging_product"`
        To               string   `json:"to"`
    }
    
    func send(c *gin.Context) {
    ...
       var payload Payload
       if err := c.Bind(&payload); err!= nil {
           // handling error binding
       }
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-20
      • 2021-11-28
      • 1970-01-01
      • 2014-09-30
      相关资源
      最近更新 更多