package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type Person struct {
Name string `form:"name" json:"name" binding:"required"`
Age int `form:"age" json:"age" binding:"required"`
Birthday string `form:"birthday" json:"birthday" binding:"required"`
}
func main() {
engine := gin.Default()
engine.POST("/form_post", form_post)
engine.POST("/json_post", json_post)
engine.Run(":8081")
}
func form_post(context *gin.Context) {
var person Person
if err := context.ShouldBind(&person); err == nil {
context.String(http.StatusOK, "form post\nHello %s!\nage: %d\nBirthday: %s\n", person.Name, person.Age, person.Birthday)
} else {
context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
}
func json_post(context *gin.Context) {
var person Person
if err := context.ShouldBindJSON(&person); err == nil {
context.String(http.StatusOK, "json post\nHello %s!\nage: %d\nBirthday: %s\n", person.Name, person.Age, person.Birthday)
} else {
context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
}