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()
}
相关推荐
Clarence Liu2 小时前
Go Map进化史:从桶链式哈希表到Swiss Table的源码级剖析
golang·哈希算法·散列表
卜锦元2 小时前
Golang后端性能优化手册(第一章:数据库性能优化)
大数据·开发语言·数据库·人工智能·后端·性能优化·golang
小高Baby@2 小时前
map的数据结构,扩容机制,key是无序的原因
数据结构·golang·哈希算法
T0uken3 小时前
Go + React 单文件 Web 应用模板开发指南
前端·react.js·golang
码luffyliu3 小时前
告别 Go 版本混乱:macOS 下工作项目与个人项目版本管理
开发语言·golang·goenv
思成Codes3 小时前
Gin 框架 JSON 全链路:从响应返回到请求绑定
golang·json·gin
思成Codes3 小时前
Gin.RouterGroup:分组、中间件与路径组合
中间件·gin
大猫熊猫3 小时前
【ios】xcode运行项目时报错 Showing All Errors Only Framework ‘Pods_Runner‘ not found
macos·ios·xcode
天天向上102416 小时前
go 配置热更新
开发语言·后端·golang