doujun5009 2019-06-18 04:11
浏览 6
已采纳

在Golang中获取帖子请求失败

I new using Go, I have a problem how to get post request on Go. I was searching but still can't solve the problem

I was trying json.Unmarshal() but still not working

package controllers

import (
    "encoding/json"
    "net/http"

    "github.com/gin-gonic/gin"
)

//CreateOrder function
func CreateOrder(c *gin.Context) {

    var requestBody struct {
        TransNo string `json:"trans_no"`
    }

    err := json.NewDecoder(c.Request.Body).Decode(&requestBody)

    if err != nil {
        panic(err)
    }

    c.JSON(http.StatusOK, gin.H{"data": requestBody.TransNo})

}

I no have any errors, but the result not showing anything.

this my post data :

{
  "transaction_details": {
    "trans_no": "12400099",
    "gross_amount": 50000
  }
}

I wont to get trans_no value

  • 写回答

1条回答 默认 最新

  • dpwo36915 2019-06-18 04:21
    关注

    Your requestBody struct would unmarshal correctly if your post data was:

    {
        "trans_no": "12400099",
        "gross_amount": 50000
    }
    

    but since that information is nested one deeper, you need to include that nesting in your model.

    var requestBody struct {
        TransactionDetails struct {
            TransNo string `json:"trans_no"`
        } `json:"transaction_details"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装powerbuilder10卡在安装程序正在运行这个页面 没有下一步任何指令
  • ¥50 微信聊天记录备份到电脑提示成功了,但还是没同步到电脑微信
  • ¥15 python怎么在已有视频文件后添加新帧
  • ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
  • ¥15 fluent里模拟降膜反应的UDF编写
  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
  • ¥15 神经网络模型一直不能上GPU