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()
}
相关推荐
呆萌很3 小时前
【GO】结构体构造函数练习题
golang
codeejun8 小时前
每日一Go-44、Go网络栈深度拆解--从 TCP 到 HTTP 的资源复用艺术
网络·tcp/ip·golang
GDAL9 小时前
Go Channel `close()` 深入全面讲解
golang·通道·close
Tomhex11 小时前
Golang内置函数总结
golang·go
XMYX-011 小时前
05 - Go 的循环与判断:语法、用法与最佳实践
开发语言·golang
被摘下的星星13 小时前
Go赋值操作的关键细节
开发语言·golang
喵了几个咪13 小时前
Go 语言 CMS 横评:风行 GoWind 对比传统 PHP/Java CMS 核心优势
java·golang·php
喵了几个咪13 小时前
Headless 架构优势:内容与展示解耦,一套 API 打通全端生态
vue.js·架构·golang·cms·react·taro·headless
Wenweno0o2 天前
0基础Go语言Eino框架智能体实战-chatModel
开发语言·后端·golang
咬_咬2 天前
go语言学习(基本数据类型)
开发语言·学习·golang·数据类型