天天看點

Gin架構路由

作者:萬通小王子王如棋

路由組的作用

Gin架構中的路由組可以幫助開發者更有效地管理Web應用程式中的路由,進而提高Web應用程式的可維護性。

  • 區分版本
  • 區分子產品

簡單的路由組

package main
import (
    "github.com/gin-gonic/gin"
)
func main() {
    router := gin.Default()
    // 簡單的路由組: v1
    v1 := router.Group("/v1")
    {
        v1.POST("/login", loginEndpoint)
        v1.POST("/submit", submitEndpoint)
        v1.POST("/read", readEndpoint)
    }
    // 簡單的路由組: v2
    v2 := router.Group("/v2")
    {
        v2.POST("/login", loginEndpoint)
        v2.POST("/submit", submitEndpoint)
        v2.POST("/read", readEndpoint)
    }
    router.Run(":8080")
}           

路由封裝

  1. main.go
package main
import (
    all_router "test/router"
    "github.com/gin-gonic/gin"
)
func main() {
    router := gin.Default()
    all_router.Router(router) // all_router是總路由的package名稱
    router.Run(":8080")
}           

2.router/router.go 總路由

package all_router
import (
    "test/controller/test01"
    "test/controller/test02"
    "github.com/gin-gonic/gin"
)
func Router(router *gin.Engine) {
    te01 := router.Group("test01")
    te02 := router.Group("test02")
    test01.Router(te01)
    test02.Router(te02)
}           

3.業務路由及業務方法

test01

controller/test01/router.go

package test01
import (
    "github.com/gin-gonic/gin"
)
func Router(test01 *gin.RouterGroup) {
    test01.GET("/", Hello)
}           

controller/test01/hello.go

package test01
import (
    "net/http"
    "github.com/gin-gonic/gin"
)
func Hello(ctx *gin.Context) {
    ctx.String(http.StatusOK, "這是test01路由組來的")
}           

test02

controller/test02/router.go

package test02
import (
    "github.com/gin-gonic/gin"
)
func Router(test01 *gin.RouterGroup) {
    test01.GET("/", Hello)
}           

controller/test02/hello.go

package test02
import (
    "net/http"
    "github.com/gin-gonic/gin"
)
func Hello(ctx *gin.Context) {
    ctx.String(http.StatusOK, "這是test02路由組來的")
}           

4.運作效果:

Gin架構路由

http://127.0.0.1:8080/test01/

Gin架構路由

http://127.0.0.1:8080/test02/

Gin架構路由

項目結構

繼續閱讀