Gin 绑定Query JSON FORM URI 示例

package main

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"net/http"
)

type PersonJson struct {
	Age     int    `json:"age" binding:"required,gt=10"`
	Address string `json:"addr" binding:"required"`
	Name    string `json:"name" binding:"required"`
}

type PersonForm struct {
	Age     int    `form:"age" json:"age" binding:"required,gt=10"`
	Address string `form:"addr" json:"addr" binding:"required"`
	Name    string `form:"name" json:"name" binding:"required"`
}

type PersonUri struct {
	Age     int    `uri:"age" binding:"required,gt=10"`
	Address string `uri:"addr" binding:"required"`
	Name    string `uri:"name" binding:"required"`
}

func main() {
	r := gin.Default()
	r.POST("/bind/json", testJson)
	r.GET("/bind/query", testQuery)
	r.POST("/bind/form", testFrom)
	r.PUT("/bind/uri/:age/:name/:addr", testUri)
	err := r.Run()
	if err != nil {
		panic(err)
	}
}

/*
curl --request POST 'http://127.0.0.1:8080/bind/json' \
--header 'Content-Type: application/json' \
--data-raw '{
    "age": 11,
    "addr": "北京",
    "name": "老大"
}'
*/
func testJson(c *gin.Context) {
	var person PersonJson
	if err := c.ShouldBindJSON(&person); err == nil {
		c.JSON(http.StatusOK, person)
	} else {
		c.String(http.StatusBadRequest, "person bing error: %v", err)
		c.Abort()
		return
	}
}

// curl --request GET 'http://127.0.0.1:8080/bind/query?age=19&addr=内蒙&name=小小'
func testQuery(c *gin.Context) {
	var person PersonForm
	if err := c.ShouldBindQuery(&person); err == nil {
		c.JSON(http.StatusOK, person)
	} else {
		c.String(http.StatusBadRequest, "person bing error: %v", err)
		c.Abort()
		return
	}
}

// curl --request PUT 'http://127.0.0.1:8080/bind/uri/20/小小/北京'
func testUri(c *gin.Context) {
	var person PersonUri
	if err := c.ShouldBindUri(&person); err == nil {
		c.JSON(http.StatusOK, person)
	} else {
		c.String(http.StatusBadRequest, "person bing error: %v", err)
		c.Abort()
		return
	}
}

/*
curl --request POST 'http://127.0.0.1:8080/bind/form' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--form 'age="20"' \
--form 'name="大大"' \
--form 'addr="天通苑"'
*/
func testFrom(c *gin.Context) {
	var person PersonForm
	if err := c.ShouldBindWith(&person, binding.Form); err == nil {
		c.JSON(http.StatusOK, person)
	} else {
		c.String(http.StatusBadRequest, "person bing error: %v", err)
		c.Abort()
		return
	}
}


上一篇:Nginx try_files


下一篇:http幂等性 post get put delete patch