🟢 1. 获取 GET 参数
GET 请求的参数一般在 URL Query String 中,如:
GET /api/user?name=Tom&id=123
Gin 中获取 GET 参数有两种方法:
✅ Query()
name := c.Query("name") // 如果没传返回 ""
id := c.Query("id")
✅ DefaultQuery()
带默认值:
name := c.DefaultQuery("name", "default_name")
✅ 示例:
func GetUser(c *gin.Context) {
name := c.Query("name")
id := c.DefaultQuery("id", "0")
c.JSON(200, gin.H{
"name": name,
"id": id,
})
}
🟢 2. 获取 POST 表单参数
如果是表单提交(Content-Type: application/x-www-form-urlencoded
或 multipart/form-data
)
✅ PostForm()
username := c.PostForm("username")
password := c.DefaultPostForm("password", "123456")
✅ 示例:
func PostForm(c *gin.Context) {
username := c.PostForm("username")
age := c.DefaultPostForm("age", "18")
c.JSON(200, gin.H{
"username": username,
"age": age,
})
}
🟢 3. 获取 JSON 请求体
如果是 Content-Type: application/json
,使用 BindJSON 解析到结构体。
✅ 示例结构体
type LoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
✅ 示例:
func Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{
"username": req.Username,
"password": req.Password,
})
}
🟢 4. 同时获取 Query 和 PostForm
有时候前端会同时传 GET + POST:
POST /api/user?from=web
✅ 示例:
func Mixed(c *gin.Context) {
from := c.Query("from")
token := c.PostForm("token")
c.JSON(200, gin.H{
"from": from,
"token": token,
})
}
🟢 5. 获取路由参数
例如路由 /user/:id
✅ 定义:
r.GET("/user/:id", GetUser)
✅ 获取:
func GetUser(c *gin.Context) {
id := c.Param("id")
c.JSON(200, gin.H{"id": id})
}
🟢 6. 总结对比
类型 | 方法 | 备注 |
---|---|---|
GET | Query() |
URL 查询参数 |
GET | DefaultQuery() |
URL 查询参数 + 默认值 |
POST Form | PostForm() |
表单参数 |
POST Form | DefaultPostForm() |
表单参数 + 默认值 |
JSON Body | ShouldBindJSON() |
请求体JSON映射结构体 |
路由参数 | Param() |
/user/:id 这种动态路由参数 |
本文为原创内容,作者:闲鹤,原文链接:https://blog.uwenya.cc/1604.html,转载请注明出处。