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()
}
相关推荐
REDcker19 小时前
RESTful API设计规范详解
服务器·后端·接口·api·restful·博客·后端开发
Clarence Liu1 天前
AI Agent开发(2) - 深入解析 A2A 协议与 Go 实战指南
开发语言·人工智能·golang
小胖红1 天前
Xcode 打包失败 处理
ide·macos·xcode
源代码•宸1 天前
Golang原理剖析(defer、defer面试与分析)
开发语言·经验分享·后端·面试·golang·defer·开放编码
且去填词1 天前
三色标记法与混合写屏障:Go GC 垃圾回收全流程解析
开发语言·算法·golang·三色标记法·gogc·屏障技术
源代码•宸1 天前
Golang原理剖析(interface)
服务器·开发语言·后端·golang·interface·type·itab
王家视频教程图书馆1 天前
go语言 gin grom jwt 登陆token验证 增删改查 分页 完整 图书管理系统
gin
汪碧康1 天前
一文掌握k8s容器的资源限制
docker·云原生·容器·golang·kubernetes·k8s·xkube
PKWjiMrlayO1 天前
LabView源码与三菱FX编程口协议通讯的实现方案
xcode
moxiaoran57532 天前
Go语言的错误处理
开发语言·后端·golang