Skip to content

Instantly share code, notes, and snippets.

@mortymacs
Created December 11, 2022 11:38
Show Gist options
  • Save mortymacs/987a629122f538104b56c643420a28ff to your computer and use it in GitHub Desktop.
Save mortymacs/987a629122f538104b56c643420a28ff to your computer and use it in GitHub Desktop.
sample binding in Gin
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
type AddressTypeAttr struct {
PostalCode string `json:"postalCode" binding:"required"`
HouseNumber uint16 `json:"houseNumber" binding:"required"`
}
type PersonTypeAddr struct {
ID string `json:"id" binding:"required"`
}
type Body struct {
ActionType string `json:"actionType" binding:"required"`
Person PersonTypeAddr `json:"person,omitempty" binding:"required_without=Address"`
Address AddressTypeAttr `json:"address,omitempty" binding:"required_without=Person"`
}
func main() {
r := gin.Default()
r.POST("/", func(ctx *gin.Context) {
b := Body{}
if err := ctx.BindJSON(&b); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("invalid request body: %s", err)})
} else {
ctx.JSON(http.StatusOK, gin.H{"data": "We got that!"})
}
})
r.Run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment