天天看點

Go Web——Gin實作路由分組普通路由路由分組路由原理

文章目錄

  • 普通路由
  • 路由分組
  • 路由原理

普通路由

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func F1(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"method": "GET",
	})
}
func F2(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"method": "POST",
	})
}
func F3(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"method": "PUT",
	})
}
func F4(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"method": "DELETE",
	})
}

func main() {
	e := gin.Default()

	e.GET("/index", F1)
	e.POST("/index", F2)
	e.PUT("/index", F3)
	e.DELETE("/index", F4)

	e.Run()
}
           

此外,還有一個可以比對所有請求方法的

Any

方法如下:

//請求方法集合
r.Any("/user", func(c *gin.Context) {

   switch c.Request.Method {
   case "GET":
      c.JSON(http.StatusOK, gin.H{"method": "GET"})
   case http.MethodPost:
      c.JSON(http.StatusOK, gin.H{"method": "POST"})
   }

   c.JSON(http.StatusOK, gin.H{
      "method": "Any",
   })
})
           

為沒有配置處理函數的路由添加處理程式,預設情況下它傳回404代碼,下面的代碼為沒有比對到路由的請求都傳回

views/404.html

頁面。

//NoRoute
r.NoRoute(func(c *gin.Context) {
   c.JSON(http.StatusNotFound, gin.H{"message": "http://www.baidu.com"})
})
           

路由分組

我們可以将擁有共同URL字首的路由劃分為一個路由組。習慣性一對

{}

包裹同組的路由,這隻是為了看着清晰,你用不用{}包裹功能上沒什麼差別。

package main

import (
	"github.com/gin-gonic/gin"
)

func F1(c *gin.Context) {}
func F2(c *gin.Context) {}
func F3(c *gin.Context) {}
func F4(c *gin.Context) {}

func main() {
	router := gin.Default()

	// 簡單的路由組: v1
	v1 := router.Group("/v1")
	{
		v1.POST("/login", F1)
		v1.POST("/submit", F2)
		v1.POST("/read", F3)
	}

	// 簡單的路由組: v2
	v2 := router.Group("/v2")
	{
		v2.POST("/login", F1)
		v2.POST("/submit", F2)
		v2.POST("/read", F3)
	}

	router.Run()
}
           

路由組也是支援嵌套的,例如:

shopGroup := r.Group("/shop")
	{
		shopGroup.GET("/index", func(c *gin.Context) {...})
		shopGroup.GET("/cart", func(c *gin.Context) {...})
		shopGroup.POST("/checkout", func(c *gin.Context) {...})
		
		// 嵌套路由組
		xx := shopGroup.Group("xx")
		xx.GET("/oo", func(c *gin.Context) {...})
	}
           

路由原理

Gin架構中的路由使用的是httprouter這個庫。

其基本原理就是構造一個路由位址的字首樹。