[英]How to replace variable struct in golang http.NewRequest POST with request body
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?我是 golang 的新手,在使用请求正文修改数据结构时遇到问题,在此代码中我想从请求正文修改 var To 基于值,该怎么做?
body: {"phone": "1989876787"}
正文:
{"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))
}
Using gin framework, You can use binding function.使用 gin 框架,您可以使用绑定 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,
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.