查看httpserver,看看是否有可能从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")
...
}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.Engine { // fasthttp: *fasthttprouter.Router
return router1 // runtime error
}
func GetRouter2() *gin.Engine {
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)
}
}运行时错误发生在return router1或return router2的route.go中。
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)
serveError: c.Next()
...我怀疑main.go中的router无法通过middleware将ctx路由到router1或router2。我是否需要在ServeHttp middleware处理程序中使用&http.Server而不是&fasthttp.Server?这通常是如何在Gin方式中完成的?
发布于 2021-09-16 15:17:46
对组使用单个引擎:
router = gin.New()
group1:=router.Group("/path1")
group2:=router.Group("/path2")然后分别配置两个组。
https://stackoverflow.com/questions/69211029
复制相似问题