[!NOTE] gin采用httprouter实现路由

  • 项目路由文件routes目录下
  • 核心注册文件routes/route.go
  • 介绍路由的基本用法

基本路由

路由器允许你注册能响应任何 HTTP 请求的路由:

    router.Any(path, ...HandlerFunc)
    router.GET(path, ...HandlerFunc)
    router.POST(path, ...HandlerFunc)
    router.DELETE(path, ...HandlerFunc)
    router.PATCH(path, ...HandlerFunc)
    router.PUT(path, ...HandlerFunc)
    router.OPTIONS(path, ...HandlerFunc)
    router.HEAD(path, ...HandlerFunc)

路由参数

// 此 handler 将匹配 /user/john/ 和 /user/john/send
    router.GET("/user/:name/*action", func(c *gin.Context) {
        name := c.Param("name")
        action := c.Param("action")
        message := name + " is " + action
        c.String(http.StatusOK, message)
    })

静态文件路由

本项目采用 r.StaticFS("/public", http.FS(f))

// example: /public/static/js/a.js

    router := gin.Default()
    router.Static("/assets", "./assets")
    router.StaticFS("/more_static", http.Dir("my_file_system"))
    router.StaticFile("/favicon.ico", "./resources/favicon.ico")

路由组

router := gin.Default()

// 简单的路由组: v1
v1 := router.Group("/v1")
{
    v1.POST("/login", loginEndpoint)
    v1.POST("/submit", submitEndpoint)
    v1.POST("/read", readEndpoint)
}

重定向

http重定向
r.GET("/test", func(c *gin.Context) {
    c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
})

路由重定向

r.GET("/test", func(c *gin.Context) {
    c.Request.URL.Path = "/test2"
    r.HandleContext(c)
})
r.GET("/test2", func(c *gin.Context) {
    c.JSON(200, gin.H{"hello": "world"})
})
powered by Gitbook该文件最后修改时间: 2021-12-02 10:36:59

results matching ""

    No results matching ""