Gin路由:构建高效RESTful API

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()
}
相关推荐
fy121631 天前
GO 快速升级Go版本
开发语言·redis·golang
2501_916007471 天前
在非 Xcode 环境下完成苹果开发编译的记录 iOS 编译与调试
ide·vscode·ios·cocoa·个人开发·xcode·敏捷流程
武超杰1 天前
SpringMVC核心功能详解:从RESTful到JSON数据处理
后端·json·restful
童话ing1 天前
【Golang】Golang Map数据结构底层原理
数据结构·golang·哈希算法
GDAL1 天前
go.mod 文件讲解
golang·go.mod
Java面试题总结1 天前
Go图像处理基础: image包深度指南
图像处理·算法·golang
robch1 天前
golang container/heap 是一个为任意类型实现堆(优先队列)接口的包
数据结构·算法·golang
leonkay2 天前
Golang语言闭包完全指南
开发语言·数据结构·后端·算法·架构·golang
2501_921649492 天前
美股历史 K线数据 API接口综合评测与接入指南
后端·python·websocket·金融·restful
echome8882 天前
Go 语言并发编程实战:用 Goroutine 和 Channel 构建高性能任务调度器
开发语言·后端·golang