Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question about middleware #1169

Closed
ghost opened this issue Nov 13, 2017 · 3 comments
Closed

Question about middleware #1169

ghost opened this issue Nov 13, 2017 · 3 comments

Comments

@ghost
Copy link

ghost commented Nov 13, 2017

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")
}
@nazwa
Copy link

nazwa commented Nov 13, 2017

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.

@ycdesu
Copy link

ycdesu commented Nov 13, 2017

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.

@ghost
Copy link
Author

ghost commented Nov 14, 2017

That`s works for me thank you guys

@ghost ghost closed this as completed Nov 14, 2017
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants