- 同过本文你可有学到Gin 框架
- Http URL参数范例
- 获取请求参数变量在url path中
- Json body 参数 与Go struct自动绑定
- Bind ShouldBind
![3f1fa8e8f64a26a943441a2b0b80900c.png](https://img-blog.csdnimg.cn/img_convert/3f1fa8e8f64a26a943441a2b0b80900c.png)
Gin 框架启动如下。请求和handler 列表一目了然。
![361ed5de178ded024656a57cd3116bcb.png](https://img-blog.csdnimg.cn/img_convert/361ed5de178ded024656a57cd3116bcb.png)
URL查询参数
(https://juejin.im/search?keyword=tony&type=admin&id=10 )
绑定 HttpURl参数
func (c *Context) GetQuery(key string) (string, bool)func (c *Context) Query(key string) stringfunc (c *Context) DefaultQuery(key, defaultValue string) stringfunc (c *Context) GetQueryArray(key string) ([]string, bool)func (c *Context) QueryArray(key string) []stringr.GET("/user/:id", func(c *gin.Context) { id,_ := c.GetQuery("keyword") //id := c.Query("keyword") //id := c.DefaultQuery("keyword","tomy") // http://localhost:8080/user?id=10&id=11&id=12 // ids := c.QueryArray("id")})
通过c.Query 可有绑定 ,同时可有通过DefaultQuery设定初始化的值
请求变量在url path中
https://juejin.im/user/:id )复制代码
注意 GET请求: /user/:id 中的:id是变量。可以变动的部分。 举例子: /user/tom, /user/tony 里面的tom, tony就是:id的不同的变量值。
那么如果在gin中获得呢
r.GET("/user/:id", func(c *gin.Context) { id, err := c.Params.Get("id")})
Json body 参数 与Go struct自动绑定
type Person struct {Name string `form:"name"`Address string `form:"address"`Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`}func startPage(c *gin.Context) {var person Person// If `GET`, only `Form` binding engine (`query`) used.// 如果是Get,那么接收不到请求中的Post的数据??// 如果是Post, 首先判断 `content-type` 的类型 `JSON` or `XML`, 然后使用对应的绑定器获取数据.if c.ShouldBind(&person) == nil {log.Println(person.Name)log.Println(person.Address)log.Println(person.Birthday)}c.String(200, "Success")}
实战中一般用json Bind 或者 ShouldBind比较方便。 post 来获取参数。
通过参数json 走动绑定。非常方便的获得浏览器前端的参数了。
![3154bc09d08aef8a02aa3a0b4eca2fee.gif](https://img-blog.csdnimg.cn/img_convert/3154bc09d08aef8a02aa3a0b4eca2fee.gif)
后续还要讲如何方便的自动验证参数!