url 参数除了通过 c.Query() 或 c.DefaultQuery() 获取值,还可以绑定到结构体。

c.ShouldBindQuery() 函数只绑定 url 查询参数而忽略 post 数据。

示例代码:

package main

import (
	"log"

	"github.com/gin-gonic/gin"
)

type Person struct {
	Name    string `form:"name"`
	Address string `form:"address"`
}

func main() {
	route := gin.Default()
	route.Any("/testing", startPage)
	route.Run(":8085")
}

func startPage(c *gin.Context) {
	var person Person
	if c.ShouldBindQuery(&person) == nil {
		log.Println("------ Only Bind By Query String ======")
		log.Println(person.Name)
		log.Println(person.Address)
	}
	c.String(200, "Success")
}

使用 curl 访问,并查看服务端控制台输出:

# 绑定URL查询字符串
$ curl -X GET "localhost:8085/testing?name=eason&address=xyz"

# 绑定URL查询字符串,POST表单同名字段会被忽略
$ curl -X POST "localhost:8085/testing?name=eason&address=xyz" -d "name=ignore&address=ignore"