I have routes like this

r1 := router.Group("/")
r1.Use(SetSiteMiddleware())
r1.GET("/posts", PostsHandler)

routesAdmin := router.Group("/api/admin")
routesAdmin.GET("/posts", AdminPostsHandler)

The website middleware is executing on the Admin Group also when i have the middleware set only on the r1 group.

The middleware should NOT run on the admin group

Comment From: academician

I tested your example, and the middleware was not run for the admin group. At least not for v1.9.0.

package main

import (
    "fmt"
    "net/http"

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

func TestMiddleware(c *gin.Context) {
    fmt.Println("Test: ", c.Request.RequestURI)
    c.Next()
}

func main() {
    r := gin.Default()

    r1 := r.Group("/")
    r1.Use(TestMiddleware)
    r1.GET("/posts", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"hello": "world"})
    })

    routesAdmin := r.Group("/api/admin")
    routesAdmin.GET("/posts", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"hello": "admin"})
    })

    r.Run(":9123")
}

After go run main.go:

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /posts                    --> main.main.func1 (4 handlers)
[GIN-debug] GET    /api/admin/posts          --> main.main.func2 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :9123
Test:  /posts
[GIN] 2023/03/16 - 12:43:18 | 200 |       526.7µs |       127.0.0.1 | GET      "/posts"
[GIN] 2023/03/16 - 12:43:24 | 200 |            0s |       127.0.0.1 | GET      "/api/admin/posts"
[GIN] 2023/03/16 - 12:43:30 | 200 |            0s |       127.0.0.1 | GET      "/api/admin/posts"
[GIN] 2023/03/16 - 12:43:31 | 200 |            0s |       127.0.0.1 | GET      "/api/admin/posts"
Test:  /posts
[GIN] 2023/03/16 - 12:43:35 | 200 |       507.1µs |       127.0.0.1 | GET      "/posts"

Comment From: khanakia

Yes, it seems fixed now after restarting the server but I still could not figure out why it was behaving like this.

Thanks for checking into this 👍 .