Created
December 11, 2022 11:38
-
-
Save mortymacs/987a629122f538104b56c643420a28ff to your computer and use it in GitHub Desktop.
sample binding in Gin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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