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

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

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

问题

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

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

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

  1. type Payload struct {
  2. MessagingProduct string `json:"messaging_product"`
  3. To string `json:"to"`
  4. }
  5. func Send(c *gin.Context) {
  6. data := Payload{
  7. MessagingProduct: "sms",
  8. To: "", // 从请求体中修改这个值
  9. }
  10. jsonStr, _ := json.Marshal(data)
  11. fmt.Println("请求体", string(jsonStr))
  12. }
英文:

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"}

  1. type Payload struct {
  2. MessagingProduct string `json:"messaging_product"`
  3. To string `json:"to"`
  4. }
  5. func Send(c *gin.Context) {
  6. data := Payload{
  7. MessagingProduct: "sms",
  8. To: "", //modify this from req body
  9. }
  10. jsonStr, _ := json.Marshal(data)
  11. fmt.Println("req body", string(jsonStr))
  12. }

答案1

得分: 2

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

  1. type Payload struct {
  2. Phone string `json:"phone"`
  3. }
  4. func Send(c *gin.Context) {
  5. ...
  6. var payload Payload
  7. if err := c.ShouldBindJSON(&payload); err != nil {
  8. // 处理绑定错误
  9. }
  10. data := Payload{
  11. MessagingProduct: "sms",
  12. To: payload.Phone,
  13. }
  14. ...
  15. }
英文:

Using gin framework, You can use binding function.

  1. type Payload struct {
  2. Phone string `json:"phone"`
  3. }
  4. func Send(c *gin.Context) {
  5. ...
  6. var payload Payload
  7. if err := c.ShouldBindJSON(&payload); err != nil {
  8. // handling error binding
  9. }
  10. data := Payload{
  11. MessagingProduct: "sms",
  12. To: paylod.Phone,
  13. }
  14. ...
  15. }

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:

确定