英文:
golang replace fasthttp to gin with slice bounds out of range runtime error
问题
看起来你正在尝试将一个使用fasthttp的http服务器切换到gin,并且在中间件的路由过程中遇到了运行时错误。你希望尽可能保持代码的相似性。
在main.go中,你将fasthttp的服务器替换为了gin的服务器。在route.go中,你定义了两个gin的路由器。然后,在middleware.go中,你尝试使用route.GetRouter1().HandleContext(cts)或route.GetRouter2().HandleContext(ctx)来处理请求。
运行时错误发生在route.go中的return router1或return router2处,错误信息显示切片索引超出范围。
我怀疑在main.go中的router无法通过middleware将ctx路由到router1或router2。你是否需要使用&http.Server替代&fasthttp.Server,并使用ServeHttp作为中间件处理程序?在Gin中,通常如何处理这种情况呢?
英文:
looking into a httpserver and see if it is possible to change from fasthttp to gin but stuck and having a runtime error during routing from middleware. I am trying to keep the code similar to each other if possible.
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)
}
}
The runtime error occurred in route.go at return router1 or 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)
serveError: c.Next()
...
I suspect the router in main.go cannot route ctx to router1 or router2 via middleware. Do I need to use &http.Server instead of &fasthttp.Server with a ServeHttp middleware handler? How would this normally be done in Gin ways?
答案1
得分: 2
使用单个引擎与分组:
router = gin.New()
group1:=router.Group("/path1")
group2:=router.Group("/path2")
然后分别配置这两个分组。
英文:
Use a single engine with groups:
router = gin.New()
group1:=router.Group("/path1")
group2:=router.Group("/path2")
Then configure both groups separately.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论