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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?