Skip to content

Instantly share code, notes, and snippets.

@konojunya
Last active November 21, 2022 09:54
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save konojunya/453fa1e5f84058fd8cb8d7c0122348e1 to your computer and use it in GitHub Desktop.
Save konojunya/453fa1e5f84058fd8cb8d7c0122348e1 to your computer and use it in GitHub Desktop.
Sample using gin's BindJSON
package main
import (
"fmt"
"log"
"github.com/gin-gonic/gin"
)
type CreateParams struct {
Username string `json:"username"`
Guests []Person `json:"guests"`
RoomType string `json:"roomType"`
CheckinDate string `json:"checkinDate"`
CheckoutDate string `json:"checkoutDate"`
}
type Person struct {
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
}
func main() {
r := gin.Default()
r.POST("/", func(c *gin.Context) {
var createParams CreateParams
err := c.BindJSON(&createParams)
if err != nil {
log.Fatal(err)
}
fmt.Println(createParams)
})
r.Run(":8000")
// request
// curl http://localhost:8000 -d @request.json
}
{
"guests": [
{
"firstname": "ryan",
"lastname": "vlaming"
}
],
"roomType": "suite",
"checkinDate": "2018-04-13T19:24:00+00:00",
"checkoutDate": "2018-07-13T19:24:00+00:00"
}
@boddumanohar
Copy link

what's the difference between c.BindJSON and json.Unmarshal?

@konojunya
Copy link
Author

@boddumanohar
I don't know because I haven't written Golang for about 2 years, but when I read the source code, c.BindJSON passes the HTTP status code 400 to the context and then returns a pointer or an error. Internally, the decoder of the json package I'm implementing using.
You can understand it by reading the following.

BindJSON: https://github.com/gin-gonic/gin/blob/e899771392ecf35de8ce10a030ed8fed2207e9cb/context.go#L608

context has 400 status code when if an error occurs

https://github.com/gin-gonic/gin/blob/e899771392ecf35de8ce10a030ed8fed2207e9cb/context.go#L647

decodeJSON: https://github.com/gin-gonic/gin/blob/e899771392ecf35de8ce10a030ed8fed2207e9cb/binding/json.go#L44

@MohammadmahdiAhmadi
Copy link

If you added 'required' tag in your struct, then in JsonBind you will receive an error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment