英文:
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,
}
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论