如何在Golang的http.NewRequest POST中使用请求体替换变量结构体

huangapple go评论72阅读模式
英文:

How to replace variable struct in golang http.NewRequest POST with request body

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我是Go语言的新手,在修改数据结构时遇到了问题。在这段代码中,我想根据请求体的值修改变量To,该如何做到?

请求体:{"phone": "1989876787"}

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

func Send(c *gin.Context) {
    data := Payload{
        MessagingProduct: "sms",
        To: "", // 从请求体中修改这个值
    }
    jsonStr, _ := json.Marshal(data)
    fmt.Println("请求体", string(jsonStr))
}
英文:

I am new in golang and i am having problem when modify data struct with request body, in this code i want to modify var To based value from request body, how to do that?

body: {"phone": "1989876787"}

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

func Send(c *gin.Context) {
	data := Payload{
		MessagingProduct: "sms",
		To: "", //modify this from req body
	}
	jsonStr, _ := json.Marshal(data)
	fmt.Println("req body", string(jsonStr))
}

答案1

得分: 2

使用gin框架,您可以使用绑定函数。

type Payload struct {
    Phone string   `json:"phone"`
}

func Send(c *gin.Context) {
...
   var payload Payload
   if err := c.ShouldBindJSON(&payload); err != nil {
       // 处理绑定错误
   }
   data := Payload{
	  MessagingProduct: "sms",
	  To:  payload.Phone,
   }
...
}
英文:

Using gin framework, You can use binding function.

type Payload struct {
    Phone string   `json:"phone"`
}

func Send(c *gin.Context) {
...
   var payload Payload
   if err := c.ShouldBindJSON(&payload); err != nil {
       // handling error binding
   }
   data := Payload{
	  MessagingProduct: "sms",
	  To:  paylod.Phone,
   }
...
}

huangapple
  • 本文由 发表于 2022年8月17日 17:44:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/73386270.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定