gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
76.72k stars 7.91k forks source link

Why execute router.Use(xxx) first and then router.NoRoute(xxx)? #3416

Open MmToon opened 1 year ago

MmToon commented 1 year ago

Description

Why execute router.Use(xxx) first and then router.NoRoute(xxx)? In addition, if it is necessary to run router.Use after occurrence of router.NoRoute? Because I did some request verification in router.Use(xxx).

How to reproduce

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()
    //The coding sequence of router.NoRoute(xxx) and router.Use(xxx) does not affect the execution result.
    router.NoRoute(func (c *gin.Context) {
        c.String(404, "404")
    })
    router.Use(func (c *gin.Context) {
        fmt.Println("init")
    })
    router.GET("/", func(c *gin.Context) {
        c.String(200, "OK")
    })
    router.Run()
}

Expectations

$ curl http://127.0.0.1:8080/other
404(But I do not want router.Use(xxx) to run.)

Actual result

$ curl http://127.0.0.1:8080/other
404(console print "init".)

Environment

MmToon commented 1 year ago

This is the way to solve the problem, in router.Use(xxx).

......
if fullPath = c.FullPath(); fullPath == "" {
    c.String(404, "404")
    c.Abort()
    return
}
......