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?
Use a single engine with groups:
router = gin.New()
group1:=router.Group("/path1")
group2:=router.Group("/path2")
Then configure both groups separately.