研究一個https服務器,看看是否有可能從fasthttp改為gin,但在從中間件路由時卡住并出現運行時錯誤。如果可能的話,我正試圖保持代碼的相似性。
main.go
func main() {
...
route.InitRouters()
/*
s := &fasthttp.Server{Handler: middleware.Handler}。// fasthttp
s.ListenAndServe(":8081")
*/
router := gin.New() // gin
router.Use(middleware.Handler)
router.Run("localhost:8180"/span>)
...
}
route.go
var router1 *gin.Engine // fasthttp: *fasthttprouter.Router
var router2 *gin.Engine
func InitRouters(){
router1 = gin.New() //fasthttp: fasthttprouter.New().
...
router2 = gin.New()
...
}
func GetRouter1() *gin。 引擎 { // fasthttp: *fasthttprouter.Router。
return router1 // runtime error
}
func GetRouter2() *gin. 引擎 {
return router2 // runtime error。
}
...
middleware.go
...
func Handler(ctx *gin.Context) { // fasthttp: ctx *fasthttp.RequestCtx
if ... {
route.GetRouter1().HandleContext(cts) // fasthttp: route.GetRouter1().Handler(ctx)
} else {
route.GetRouter2().HandleContext(ctx)
}
}
運行時錯誤發生在route.go的return router1或return router2。
runtime error: slice bounds out of range [:1] with capacity 0。
...
go/pkg/mod/github.com/gin-gonic/gin@v1.7. 4/context.go:165 (0xc4eaca)
(*Context).Next: c.handlers[c.index](c)
go/pkg/mod/github.com/gin-gonic/gin@v1.7. 4/recovery.go:99 (0xc62bcc)
CustomRecoveryWithWriter.func1: c.Next()
go/pkg/mod/github.com/gin-gonic/gin@v1.7. 4/context.go:165 (0xc4eaca)
(*Context).Next: c.handlers[c.index](c)
go/pkg/mod/github.com/gin-gonic/gin@v1.7. 4/gin.go:525(0xc59777)。
serviceError: c.Next()
...
我懷疑main.go中的router不能通過middleware將ctx路由到router1或router2。我是否需要使用&http.Server而不是&fasthttp.Server與一個ServeHttpmiddleware處理程式?通常情況下,這在Gin方式中是如何完成的?
CodePudding
使用一個帶組的單一引擎:
router = gin.New()
group1:=router.Group("/path1"/span>)
group2:=router.Group("/path2")
然后分別配置兩個組。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/329387.html
標籤:
