01
PostForm
form 传参:
func (*gin.Context).PostForm(key string) string
PostForm returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns an empty string `("")`.
urlencoded form 和 multipart form:
urlencoded form 数据被编码成以 '&' 分隔的键-值对, 同时以 '=' 分隔键和值. 非字母或数字的字符会被 percent-encoding。
multipart form 支持二进制数据。
02
DefaultPostForm
form 传参:
func (*gin.Context).DefaultPostForm(key string, defaultValue string) string
DefaultPostForm returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns the specified defaultValue string.
更多信息,查看 PostForm() and GetPostForm()。
03
Query
URL 传参
func (*gin.Context).Query(key string) string
Query returns the keyed url query value if it exists, otherwise it returns an empty string `("")`.
它是 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") == ""
04
DefaultQuery
URL 传参
func (*gin.Context).DefaultQuery(key string, defaultValue string) string
DefaultQuery returns the keyed url query value if it exists, otherwise it returns the specified defaultValue string.
更多信息,查看 Query() and GetQuery()。
示例:
GET /?name=Manu&lastname= c.DefaultQuery("name", "unknown") == "Manu" c.DefaultQuery("id", "none") == "none" c.DefaultQuery("lastname", "none") == ""
05
PostFormMap
form 传参:
func (*gin.Context).PostFormMap(key string) map[string]string
PostFormMap returns a map for a given form key.
06
QueryMap
URL 传参:
func (*gin.Context).QueryMap(key string) map[string]string
QueryMap returns a map for a given query key.
示例代码:
请求示例:
curl --location --request POST 'http://localhost:8081/user?tel=13800138000&email=lucy@gmail.com&sex=girl&score[a]=66&score[b]=88' \ --form 'name=lucy' \ --form 'age=17' \ --form 'level[chinese]=1' \ --form 'level[english]=2'
07
Param
URI 传参:
func (*gin.Context).Param(key string) string
Param returns the value of the URL param.
它是 c.Params.ByName(key) 的一种快捷方式。
示例:
router.GET("/user/:id", func(c *gin.Context) { // a GET request to /user/john id := c.Param("id") // id == "john" })
08
DataFromReader
func (*gin.Context).DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string)
DataFromReader writes the specified reader into the body stream and updates the HTTP code.
示例代码: