- With issues: Unregistered routes will trigger global middleware
Description
If an unregistered route enters, 404 should be returned directly, but the middleware will be triggered.
How to reproduce
package main
import (
"fmt"
"os"
"os/signal"
"github.com/gin-gonic/gin"
)
func middle(c *gin.Context) {
fmt.Println("do middleware")
}
func InitRouter() *gin.Engine {
gine := gin.New()
gine.NoRoute(func(ctx *gin.Context) {
ctx.AbortWithStatus(404)
})
gine.Use(middle)
gine.GET("/lala", func(ctx *gin.Context) {
ctx.JSON(200, map[string]string{"msg": "ok"})
})
return gine
}
func main() {
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
go func() {
<-ch
fmt.Println("\nexited")
os.Exit(1)
}()
gin.SetMode(gin.ReleaseMode)
router := InitRouter()
fmt.Println(router.Run(":2002"))
}
Expectations
$ curl $host:2002/greet
terminal will not output 'do middleware'
Actual result
$ curl $host:2002/greet
terminal will output 'do middleware'
Comment From: Rishikesh01
Hi, @oswaldoooo this is an expected behavior of gin as middleware is just another handler , IMO this is not a bug but a design choice of Gin.
Comment From: brandon1024
Seconded @Rishikesh01 's comment. This is expected. This allows middleware to handle or modify requests that are not specifically registered with the engine but still expected to be handled.