首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >golang用切片边界超出范围运行时错误替换fasthttp to gin

golang用切片边界超出范围运行时错误替换fasthttp to gin
EN

Stack Overflow用户
提问于 2021-09-16 15:14:36
回答 1查看 198关注 0票数 2

查看httpserver,看看是否有可能从fasthttp更改为gin,但在从中间件路由过程中出现运行时错误。如果可能的话,我会尽量保持代码的相似性。

main.go

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
...
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 router1return router2route.go中。

代码语言:javascript
运行
复制
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无法通过middlewarectx路由到router1router2。我是否需要在ServeHttp middleware处理程序中使用&http.Server而不是&fasthttp.Server?这通常是如何在Gin方式中完成的?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-16 15:17:46

对组使用单个引擎:

代码语言:javascript
运行
复制
 router = gin.New()           
 group1:=router.Group("/path1")
 group2:=router.Group("/path2")

然后分别配置两个组。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69211029

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档