I have a problem how to get post request on Go.
I was trying json.Unmarshal()
but its 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 want to get trans_no
value
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"`
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.