gin的正則路由

gin-正則路由

// gin 正則路由:
type route struct {
	reg *regexp.Regexp // 正則表達式
	method string // 請求方式
	//handler func(http.ResponseWriter, *http.Request) // 處理器
	handler func(c *gin.Context) // 處理器
}
var routes = []route{
	// git clone 第一步:拉取info/refs文件:通過 update-server-info 命令生成的
	{regexp.MustCompile(`(.*?)/info/refs$`), "GET", getInfoRefs},
	// git clone 第二步:獲取HEAD
	//{regexp.MustCompile(`(.*?)/head$`), "GET", getTextFile},
	//{regexp.MustCompile(`(.*?)git-upload-pack$`), "POST", gitUpLoadPack},
}
func main() {
	router := gin.Default()
	router.Any("/*action", func(c *gin.Context) {
		// 使用正則路由表,url不需要參數
		url := strings.ToLower(c.Request.URL.Path)
		for _, route := range routes {
			if route.reg.MatchString(url) {
				if c.Request.Method == route.method {
					route.handler(c)
				}
			}
		}
	})
	router.Run(":8800")
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章