HTTP 方法路由
URL 请求 → 路由匹配 → 执行处理函数 → 返回响应
1. 基础 HTTP 方法
go
func main() {
r := gin.Default()
// GET: 获取资源
r.GET("/users", func(c *gin.Context) {
c.JSON(200, gin.H{"message": "Get all users"})
})
// POST: 创建资源
r.POST("/users", func(c *gin.Context) {
c.JSON(201, gin.H{"message": "Create user"})
})
// PUT: 更新资源(完全替换)
r.PUT("/users/:id", func(c *gin.Context) {
id := c.Param("id")
c.JSON(200, gin.H{"message": "Update user", "id": id})
})
// DELETE: 删除资源
r.DELETE("/users/:id", func(c *gin.Context) {
id := c.Param("id")
c.JSON(200, gin.H{"message": "Delete user", "id": id})
})
// PATCH: 部分更新
r.PATCH("/users/:id", func(c *gin.Context) {
id := c.Param("id")
c.JSON(200, gin.H{"message": "Partial update", "id": id})
})
r.Run()
}
2. HEAD 和 OPTIONS
go
// HEAD: 获取资源元信息(只返回头,不返回体)
r.HEAD("/users/:id", func(c *gin.Context) {
// 检查用户是否存在,返回状态码和头信息
c.Status(200)
})
// OPTIONS: 获取资源支持的 HTTP 方法
r.OPTIONS("/users", func(c *gin.Context) {
c.Header("Allow", "GET, POST, PUT, DELETE")
c.Status(200)
})
路径参数(Path Parameters)
1. 单个参数
go
r.GET("/users/:id", func(c *gin.Context) {
id := c.Param("id") // 获取路径参数
c.JSON(200, gin.H{"user_id": id})
})
// 访问: /users/123 → id = "123"
2. 多个参数
go
r.GET("/users/:userId/posts/:postId", func(c *gin.Context) {
userId := c.Param("userId")
postId := c.Param("postId")
c.JSON(200, gin.H{
"user_id": userId,
"post_id": postId,
})
})
// 访问: /users/123/posts/456 → userId="123", postId="456"
3. 可选参数(通配符)
go
// 完全通配符
r.GET("/static/*filepath", func(c *gin.Context) {
filepath := c.Param("filepath") // 包含 / 的剩余部分
c.JSON(200, gin.H{"file": filepath})
})
// 访问: /static/css/style.css → filepath="/css/style.css"
// 带前缀的通配符
r.GET("/docs/:section/*subpath", func(c *gin.Context) {
section := c.Param("section")
subpath := c.Param("subpath")
c.JSON(200, gin.H{
"section": section,
"subpath": subpath,
})
})
// 访问: /docs/api/v1/users → section="api", subpath="/v1/users"
特殊路由方法
1. Any 方法
go
// 匹配所有 HTTP 方法
r.Any("/all", func(c *gin.Context) {
method := c.Request.Method
c.JSON(200, gin.H{"method": method, "message": "All methods accepted"})
})
2. Handle 方法(自定义方法)
go
// 自定义 HTTP 方法
r.Handle("CUSTOM", "/custom", func(c *gin.Context) {
c.JSON(200, gin.H{"method": "CUSTOM", "message": "Custom method"})
})
路由参数获取
1. 路径参数
go
r.GET("/users/:id", func(c *gin.Context) {
id := c.Param("id")
// 或者获取所有参数
params := c.Params // []gin.Param 类型
for _, param := range params {
fmt.Printf("Key: %s, Value: %s\n", param.Key, param.Value)
}
})
2. 查询参数
go
r.GET("/search", func(c *gin.Context) {
keyword := c.Query("q") // 获取查询参数
page := c.DefaultQuery("page", "1") // 获取参数,有默认值
c.JSON(200, gin.H{
"keyword": keyword,
"page": page,
})
})
// 访问: /search?q=golang&page=2
完整示例:用户管理系统路由
go
func main() {
r := gin.Default()
// 用户相关路由
r.GET("/users", func(c *gin.Context) {
// 获取用户列表
c.JSON(200, gin.H{
"users": []gin.H{
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
},
"total": 2,
})
})
r.GET("/users/:id", func(c *gin.Context) {
// 获取单个用户
id := c.Param("id")
c.JSON(200, gin.H{
"id": id,
"name": "User " + id,
})
})
r.POST("/users", func(c *gin.Context) {
// 创建用户
var user struct {
Name string `json:"name"`
Email string `json:"email"`
}
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
c.JSON(201, gin.H{
"message": "User created",
"user": user,
})
})
r.PUT("/users/:id", func(c *gin.Context) {
// 更新用户
id := c.Param("id")
var updates map[string]interface{}
if err := c.ShouldBindJSON(&updates); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{
"message": "User updated",
"user_id": id,
"updates": updates,
})
})
r.DELETE("/users/:id", func(c *gin.Context) {
// 删除用户
id := c.Param("id")
c.JSON(200, gin.H{
"message": "User deleted",
"user_id": id,
})
})
r.Run()
}