Golang学习之网络参数请求-Query Params及Path Variables的区别及底层实现
背景
后端向web页面请求参数时,通常会有两种方式,1、Query Params
;2、Path Variables
,他们的区别在哪里呢?
一、Query Params
顾名思义,请求参数。由前端通过k-v键值对的形式传入,其值并不是通过url本身获取,例如
http://localhost:8080/Local/user?userName="nick"&age=12
上述链接可以分两段来理解,?
前为路径,?
后为路径传入的参数
路径:http://localhost:8080/Local/user
参数:userName="nick"
,age=12
二、Path Variables
路径参数。直接在url
中获取的参数,例如
http://localhost:8080/Local/user/nick
上述链接就是一条路径,变量nick
通过路径获取
后端接口会表示为
http://localhost:8080/Local/user/:userName
Golang实现
在gin框架中,通过context.go
封装了获取上述两种参数的方法,需通过Context
结构体调用。
什么是Context
官方的说法是,Context
是gin框架中最重要的部分,它使得我们可以在中间件中传递参数、管理数据流,验证JSON请求,渲染JSON返回流。其中封装了非常多的功能,详细阅读请查看源码或文档。
// Context is the most important part of gin. It allows us to pass variables between middleware,
// manage the flow, validate the JSON of a request and render a JSON response for example.
1、获取Query Params
提供了方法Query
,gin中部分源码如下
// Query returns the keyed url query value if it exists,
// otherwise it returns an empty string `("")`.
// It is shortcut for `c.Request.URL.Query().Get(key)`
// GET /path?id=1234&name=Manu&value=
// c.Query("id") == "1234"
// c.Query("name") == "Manu"
// c.Query("value") == ""
// c.Query("wtf") == ""
func (c *Context) Query(key string) string {
value, _ := c.GetQuery(key)
return value
}
//查看GetQury方法实现,底层通过map去接收参数,获取第一个参数值并返回
// It is shortcut for `c.Request.URL.Query().Get(key)`
// GET /?name=Manu&lastname=
// ("Manu", true) == c.GetQuery("name")
// ("", false) == c.GetQuery("id")
// ("", true) == c.GetQuery("lastname")
func (c *Context) GetQuery(key string) (string, bool) {
if values, ok := c.GetQueryArray(key); ok {
return values[0], ok
}
return "", false
}
1、获取Path Variables
提供了方法Param
// Param returns the value of the URL param.
// It is a shortcut for c.Params.ByName(key)
// router.GET("/user/:id", func(c *gin.Context) {
// // a GET request to /user/john
// id := c.Param("id") // id == "john"
// })
func (c *Context) Param(key string) string {
return c.Params.ByName(key)
}
//继续查看调用方法,使用Params结构体封装
// ByName returns the value of the first Param which key matches the given name.
// If no matching Param is found, an empty string is returned.
func (ps Params) ByName(name string) (va string) {
va, _ = ps.Get(name)
return
}
总结
1、从微观角度看,两者区别在于Path Variables
通过slice获取,而Query Params
通过map获取,关键点为是否构成k-v结构,所以当所请求参数为空值的时候,作为切片的Path Variables
是无法成功获取参数的,而map可以通过例如"name"=""
来接收参数,然后后台可以根据这个""
继续处理后续接口。
2、从宏观角度看,两者在参数获取形式上有区别。Path Variables
通过url获取,Query Params
通过请求参数获取。