gin的参数获取
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
fmt.Println(123123)
router := gin.Default()
router.GET("/", func(ctx *gin.Context) {
fmt.Println("hello gin")
ctx.String(http.StatusOK, "hello gin")
})
router.POST("/test", Test)
router.Run(":8000")
}
func Test(ctx *gin.Context) {
fmt.Println("test")
//name := ctx.Query("name") //单个获取get url里的传参 ?name=lisi&age=2
//age := ctx.PostForm("age") //单个获取post from 表单里的数据 接收post form-data或者x-www-unlencoded的值
//tag 里的 json 是接收post raw json里的值 form 是接收post form-data或者x-www-unlencoded的值
type headerParam struct {
Token string `json:"token" form:"token" binding:"required"`
Platfrom int `json:"platfrom" form:"platfrom"`
}
var h headerParam
err := ctx.BindHeader(&h) //指量获取hearder头里的信息
if err != nil {
fmt.Println("get headerParam fail , err:",err.Error())
}
type param struct {
Name string `json:"name" form:"name" binding:"required"`
Age int `json:"age" form:"age"`
Gender int `json:"gender" form:"gender"`
}
var p param
ctx.Bind(&p) //指量获取 post 是接收post form-data或者x-www-unlencoded的值 或都 raw json
//if ctx.ShouldBind(&p) == nil { //批量获取 post form-data 或者 x-www-form-urlencoded的传值
// log.Println(p.Age)
//}
ctx.ShouldBindQuery(&p) //批量获取url地址上的传参 ?name=lisi&age=2
fmt.Println(p)
ctx.JSON(http.StatusOK, gin.H{
"code": 200,
"data": p,
"header": h,
})
}
header参数
[{"key":"token","value":"123123","description":"","type":"text","enabled":true},{"key":"platfrom","value":"1","description":"","type":"text","enabled":true}]
post Raw json 请求示例
{
"age": 18,
"name": "haima1"
}
更新说明:
https://gin-gonic.com/zh-cn/docs/quickstart/
https://www.kancloud.cn/shuangdeyu/gin_book/949429
https://www.jianshu.com/p/98965b3ff638/