Gin: Question about middleware

Created on 13 Nov 2017  ·  3Comments  ·  Source: gin-gonic/gin

Hello all, i would like to ask is it possible to set middleware after handler executing.
Because in code example i provide middleware "after" does not working. Please tell me if i do something
wrong

package main

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

func middleware(t string) func(c *gin.Context) {
    return func(c *gin.Context) {
        fmt.Println(t)
    }
}

func handler(c *gin.Context) {
    fmt.Println("handler")
}

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

    v1 := router.Group("/v1")
    v1.Use(middleware("before handler"))
    v1.GET("/", handler)
        # this middleware does not execute after handler
    v1.Use(middleware("after"))

    router.Run(":3001")
}

Most helpful comment

There's a before/after request sample in README.md. In c.Next(), it uses index property of context to record what handler is running. If you want to run your after codes, just add it after c.Next() like previous answer, or register it as the final handler. The routergroup.GET method signature is func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes, so you can register handlers by GET("/", h1, h2, afterHandler). All the handlers are appended into a slice and executed in first in first out order.

All 3 comments

Yes, after execution works, but not the way you've done it :)

func before() gin.HandlerFunc {
    return func(c *gin.Context) {
        fmt.Println("before")
                c.Next()
    }
}


func after() gin.HandlerFunc {
    return func(c *gin.Context) {
                c.Next()
        fmt.Println("after")
    }
}

As you can see, everything depends on the placement of the c.Next() line.

There's a before/after request sample in README.md. In c.Next(), it uses index property of context to record what handler is running. If you want to run your after codes, just add it after c.Next() like previous answer, or register it as the final handler. The routergroup.GET method signature is func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes, so you can register handlers by GET("/", h1, h2, afterHandler). All the handlers are appended into a slice and executed in first in first out order.

That`s works for me thank you guys

Was this page helpful?
0 / 5 - 0 ratings