gin路由相關(guān)方法
c.Request.URL.Path 拿到請求的路徑
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
//路由重定向,請求轉(zhuǎn)發(fā),ANY ,NoRoute,路由組
func main() {
r := gin.Default()
// ---------------路由重定向(到其他網(wǎng)址)---------------------
r.GET("/index", func(c *gin.Context) {
//c.IndentedJSON(200,gin.H{
// "status":"ok",
//})
// 重定向到另一個地址
c.Redirect(http.StatusMovedPermanently, "https://dashen.tech")
})
// ---------------轉(zhuǎn)發(fā)(到其他接口)---------------------
r.GET("/a", func(c *gin.Context) {
// 跳轉(zhuǎn)到 /b對應的路由; 地址欄的URL不會變,是請求轉(zhuǎn)發(fā) (而上面是**重定向**到https://dashen.tech,地址欄的地址改變了)
c.Request.URL.Path = "/b" //把請求的URL修改
r.HandleContext(c) //繼續(xù)后續(xù)的處理
})
r.GET("/b", func(context *gin.Context) {
context.IndentedJSON(200, gin.H{
"status": "這是b路徑,請求成功!",
})
})
// ---------------Any: 任意http method(適用于restful,因為有同名的不同http method的方法)---------------------
// 路徑為/test的,不管是GET還是POST或者PUT等,均路由到這里
r.Any("/test", func(c *gin.Context) {
switch c.Request.Method {
case http.MethodGet:
c.IndentedJSON(200, gin.H{
"info": "api為/test,GET方式~",
})
case "POST":
c.IndentedJSON(200, gin.H{
"info": "api為/test,POST方式~",
})
}
})
// --------------------NoRoute: 當匹配不到路徑時到這里(其實gin默認有個404,取代之)--------------------
r.NoRoute(func(c *gin.Context) {
c.IndentedJSON(http.StatusNotFound, gin.H{
"msg": "任何沒有匹配到的路徑都會走到這里...(可以重定向到 尋找走丟兒童的網(wǎng)站)",
})
})
// // ----------------Group: 路由組--------------------
//把公用的前綴提取出來,創(chuàng)建一個路由組
userGroup := r.Group("/user")
{ //通常加一個大括號 讓代碼看起來更有調(diào)理
userGroup.GET("/getName", func(context *gin.Context) {
//等價于 /user/getname
context.IndentedJSON(http.StatusOK, gin.H{
"name": "張三",
})
})
userGroup.GET("/getGender", func(context *gin.Context) {
context.IndentedJSON(200, gin.H{
"gender": "男",
})
})
userGroup.POST("/updateAvatar", func(context *gin.Context) {
context.IndentedJSON(http.StatusOK, gin.H{
"msg": "頭像更新成功",
})
})
// 可以嵌套路由組
// 即 /user/address
addressGroup := userGroup.Group("/address")
// 即/user/address/city
addressGroup.GET("/city", func(c *gin.Context) {
c.IndentedJSON(200, gin.H{
"city": "阿姆斯特丹",
})
})
}
fmt.Println("路由規(guī)則初始化完畢")
r.Run()
//go func() {
// r.Run()
//}()
//select {}
}
路由重定向
轉(zhuǎn)發(fā)
Any: 捕獲同名接口的任意http method
多方式匹配,包括:
GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE
NoRoute: 當匹配不到路徑時到這里
路由組
默認區(qū)分大小寫
通配符匹配
對于接口 /v1/say/xxxx接口(POST方法,參數(shù)為body里傳一個name類型的json),當say后面為任意字符時,均路由到helloHandler方法進行處理
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
// Param 請求參數(shù)
type Param struct {
Name string `json:"name"`
}
// helloHandler /hello請求處理函數(shù)
func helloHandler(c *gin.Context) {
var p Param
if err := c.ShouldBindJSON(&p); err != nil {
c.JSON(http.StatusOK, gin.H{
"msg": "name參數(shù)缺失",
})
return
}
c.JSON(http.StatusOK, gin.H{
"msg": fmt.Sprintf("hello %s", p.Name),
})
}
// SetupRouter 路由
func SetupRouter() *gin.Engine {
router := gin.Default()
//router.POST("/v1/say/hello", helloHandler)
//router.POST("/v1/say/hello1", helloHandler)
//router.POST("/v1/say/hello3", helloHandler)
//router.POST("/v1/say/asdfg", helloHandler)
// 需要/v1/task/后面任意路徑,均路由到 helloHandler
router.POST("/v1/say/*any678", helloHandler)
return router
}
func main() {
g := SetupRouter()
g.Run() // listen and serve on 0.0.0.0:8080
}
*需要加任意字符,但不能不加(只寫*的話會報錯)
參考:
Gin框架 路由重定向,請求轉(zhuǎn)發(fā),ANY ,NoRoute,路由組
我給 gin 提交了一行代碼
Gin group級別的NoRoute
未知調(diào)用方式,靜態(tài)資源返回,靜態(tài)資源目錄等,可參考 Golang Gin 框架 Route備注
兩種寫法的比較
r.Run()
和
go func() {
r.Run()
}()
select {}
第一種方式是同步的,上面的所有路由都加載完,才會運行服務(wù)
第二種方式是異步的,假設(shè)有這樣一種情況,前面的路由解析都很快,但在解析最后幾個路由時,特別慢(當然現(xiàn)實情況不太可能)。那可以把r.Run()以異步的形式寫在最上面,即啟動服務(wù)和加載路由同步進行。那前面已解析的路由就可以訪問了
如:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
//路由重定向,請求轉(zhuǎn)發(fā),ANY ,NoRoute,路由組
func main() {
r := gin.Default()
go func() {
r.Run()
}()
// ---------------路由重定向(到其他網(wǎng)址)---------------------
r.GET("/index", func(c *gin.Context) {
//c.IndentedJSON(200,gin.H{
// "status":"ok",
//})
// 重定向到另一個地址
c.Redirect(http.StatusMovedPermanently, "https://dashen.tech")
})
// ---------------轉(zhuǎn)發(fā)(到其他接口)---------------------
r.GET("/a", func(c *gin.Context) {
// 跳轉(zhuǎn)到 /b對應的路由; 地址欄的URL不會變,是請求轉(zhuǎn)發(fā) (而上面是**重定向**到https://dashen.tech,地址欄的地址改變了)
c.Request.URL.Path = "/b" //把請求的URL修改
r.HandleContext(c) //繼續(xù)后續(xù)的處理
})
r.GET("/b", func(context *gin.Context) {
context.IndentedJSON(200, gin.H{
"status": "這是b路徑,請求成功!",
})
})
// ---------------Any: 任意http method(適用于restful,因為有同名的不同http method的方法)---------------------
// 路徑為/test的,不管是GET還是POST或者PUT等,均路由到這里
r.Any("/test", func(c *gin.Context) {
switch c.Request.Method {
case http.MethodGet:
c.IndentedJSON(200, gin.H{
"info": "api為/test,GET方式~",
})
case "POST":
c.IndentedJSON(200, gin.H{
"info": "api為/test,POST方式~",
})
}
})
time.Sleep(86400 * time.Second) // 假設(shè)下面的路由1天后才會解析
// --------------------NoRoute: 當匹配不到路徑時到這里(其實gin默認有個404,取代之)--------------------
r.NoRoute(func(c *gin.Context) {
c.IndentedJSON(http.StatusNotFound, gin.H{
"msg": "任何沒有匹配到的路徑都會走到這里...(可以重定向到 尋找走丟兒童的網(wǎng)站)",
})
})
// ----------------Group: 路由組--------------------
//把公用的前綴提取出來,創(chuàng)建一個路由組
userGroup := r.Group("/user")
{ //通常加一個大括號 讓代碼看起來更有調(diào)理
userGroup.GET("/getName", func(context *gin.Context) {
//等價于 /user/getname
context.IndentedJSON(http.StatusOK, gin.H{
"name": "張三",
})
})
userGroup.GET("/getGender", func(context *gin.Context) {
context.IndentedJSON(200, gin.H{
"gender": "男",
})
})
userGroup.POST("/updateAvatar", func(context *gin.Context) {
context.IndentedJSON(http.StatusOK, gin.H{
"msg": "頭像更新成功",
})
})
// 可以嵌套路由組
// 即 /user/address
addressGroup := userGroup.Group("/address")
// 即/user/address/city
addressGroup.GET("/city", func(c *gin.Context) {
c.IndentedJSON(200, gin.H{
"city": "阿姆斯特丹",
})
})
}
fmt.Println("路由規(guī)則初始化完畢")
select {}
}
可見,已解析的路由可正常訪問,未解析的訪問則會404
想要了解Go更多內(nèi)容,歡迎掃描下方??關(guān)注公眾號,回復關(guān)鍵詞 [實戰(zhàn)群] ,就有機會進群和我們進行交流
評論
圖片
表情
