go - golang 将 fasthttp 替换为 gin 切片边界超出范围运行时错误
问题描述
查看 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)
}
}
运行时错误发生在route.go
atreturn 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)
serveError: c.Next()
...
我怀疑router
inmain.go
无法路由ctx
到router1
或router2
via middleware
。我需要使用&http.Server
而不是&fasthttp.Server
使用ServeHttp
middleware
处理程序吗?这通常如何以 Gin 方式完成?
解决方案
将单个引擎与组一起使用:
router = gin.New()
group1:=router.Group("/path1")
group2:=router.Group("/path2")
然后分别配置这两个组。
推荐阅读
- php - Laravel:如何获取附加到正在使用的模型的模型的 ID
- matlab - 将 Matlab 命令行窗口返回到 cmd
- angular - 在 mat-option 中使用 [(indeterminate)] 属性
- dialogflow-es - 在谷歌对话流中管理意图
- jmeter - 如何通过 Jmeter GUI 使用无头浏览器
- python - 在进行二进制操作时,如何让我的 Python `set` 和 `frozenset` 子类保留它们的类型?
- google-apps-script - Google 表单上传文件 - 使用/修改响应
- ruby-on-rails - `Event.where("start_time >= ?", DateTime.now)` 不起作用
- swift - Swift 脚本鼠标移动在 scheduleTimer 中不可靠
- spring - Spring:如何保证多参数相关性