605 字
3 分钟
路由系统
路由分组
func main() { r := gin.Default()
// API v1 分组 v1 := r.Group("/api/v1") { v1.GET("/users", getUsers) v1.GET("/users/:id", getUser) v1.POST("/users", createUser) v1.PUT("/users/:id", updateUser) v1.DELETE("/users/:id", deleteUser) }
// API v2 分组 v2 := r.Group("/api/v2") { v2.GET("/users", getUsersV2) v2.POST("/users", createUserV2) }
// 管理员路由分组(带中间件) admin := r.Group("/admin") admin.Use(AuthMiddleware()) { admin.GET("/dashboard", getDashboard) admin.GET("/users", getAdminUsers) }
r.Run(":8080")}
func getUsers(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"version": "v1", "users": []string{}})}
func getUser(c *gin.Context) { id := c.Param("id") c.JSON(http.StatusOK, gin.H{"id": id})}
func createUser(c *gin.Context) { c.JSON(http.StatusCreated, gin.H{"message": "User created"})}
func updateUser(c *gin.Context) { id := c.Param("id") c.JSON(http.StatusOK, gin.H{"message": "User updated", "id": id})}
func deleteUser(c *gin.Context) { id := c.Param("id") c.JSON(http.StatusOK, gin.H{"message": "User deleted", "id": id})}
func getUsersV2(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"version": "v2", "users": []string{}})}
func createUserV2(c *gin.Context) { c.JSON(http.StatusCreated, gin.H{"message": "User created (v2)"})}
func getDashboard(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"dashboard": "data"})}
func getAdminUsers(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"admin_users": []string{}})}
func AuthMiddleware() gin.HandlerFunc { return func(c *gin.Context) { // 认证逻辑 token := c.GetHeader("Authorization") if token == "" { c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) c.Abort() return } c.Next() }}基本路由
package main
import ( "github.com/gin-gonic/gin" "net/http")
func main() { r := gin.Default()
// GET 请求 r.GET("/get", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"method": "GET"}) })
// POST 请求 r.POST("/post", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"method": "POST"}) })
// PUT 请求 r.PUT("/put", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"method": "PUT"}) })
// DELETE 请求 r.DELETE("/delete", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"method": "DELETE"}) })
// PATCH 请求 r.PATCH("/patch", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"method": "PATCH"}) })
// HEAD 请求 r.HEAD("/head", func(c *gin.Context) { c.Status(http.StatusOK) })
// OPTIONS 请求 r.OPTIONS("/options", func(c *gin.Context) { c.Status(http.StatusOK) })
r.Run(":8080")}参数路由
func main() { r := gin.Default()
// 路径参数 r.GET("/user/:name", func(c *gin.Context) { name := c.Param("name") c.JSON(http.StatusOK, gin.H{ "name": name, }) })
// 多个路径参数 r.GET("/user/:name/:id", func(c *gin.Context) { name := c.Param("name") id := c.Param("id") c.JSON(http.StatusOK, gin.H{ "name": name, "id": id, }) })
// 通配符参数(匹配所有路径) r.GET("/files/*filepath", func(c *gin.Context) { filepath := c.Param("filepath") c.JSON(http.StatusOK, gin.H{ "filepath": filepath, }) })
r.Run(":8080")}查询参数
func main() { r := gin.Default()
// 获取查询参数 r.GET("/search", func(c *gin.Context) { // 获取单个参数 query := c.Query("q")
// 获取参数(带默认值) page := c.DefaultQuery("page", "1")
// 获取参数(返回是否存在) sort, exists := c.GetQuery("sort")
c.JSON(http.StatusOK, gin.H{ "query": query, "page": page, "sort": sort, "exists": exists, }) })
// 获取数组参数 r.GET("/tags", func(c *gin.Context) { tags := c.QueryArray("tag") c.JSON(http.StatusOK, gin.H{ "tags": tags, }) })
r.Run(":8080")}表单参数
func main() { r := gin.Default()
// 单个表单字段 r.POST("/form", func(c *gin.Context) { username := c.PostForm("username") password := c.DefaultPostForm("password", "default")
c.JSON(http.StatusOK, gin.H{ "username": username, "password": password, }) })
// 表单数组 r.POST("/form-array", func(c *gin.Context) { hobbies := c.PostFormArray("hobby") c.JSON(http.StatusOK, gin.H{ "hobbies": hobbies, }) })
// 表单 Map r.POST("/form-map", func(c *gin.Context) { ids := c.QueryMap("ids") names := c.PostFormMap("names")
c.JSON(http.StatusOK, gin.H{ "ids": ids, "names": names, }) })
r.Run(":8080")}其它路由方式
func main() { r := gin.Default()
// Any 方法(匹配所有 HTTP 方法) r.Any("/any", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "method": c.Request.Method, }) })
// 静态文件服务 r.Static("/assets", "./assets") r.StaticFS("/static", http.Dir("./static")) r.StaticFile("/favicon.ico", "./favicon.ico")
// NoRoute(404 处理) r.NoRoute(func(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{ "error": "Page not found", }) })
r.Run(":8080")}分享文章
生成精美分享图或复制链接,与更多人分享本文。
继续阅读
换条路线
从其他文章中稳定抽取
最后更新于 ,距今已过 89 天
部分内容可能已过时