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

context.Next() #105

Open
achempak-polymer opened this issue Apr 22, 2023 · 2 comments
Open

context.Next() #105

achempak-polymer opened this issue Apr 22, 2023 · 2 comments

Comments

@achempak-polymer
Copy link

The docs say that examples using next should be present in this repo (https://pkg.go.dev/github.com/gin-gonic/gin#Context.Next). I'm a bit confused on the lifecycle of middleware. For example, say we have the following middleware:

func timerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		t1 := time.Now()
		c.Next()
                t2 := time.Now().Sub(t1)
                c.Header("time", t2.Seconds())
	}
}

My goal here is to include the time it took to process the request as a response header. Is the above correct way of doing this?

@FarmerChillax
Copy link
Contributor

FarmerChillax commented May 15, 2024

This is incorrect, the header has been written to the http response stream in the render method

@SteveFromAccounting
Copy link

I had some trouble finding the example documentation in Github like the comment stated, but the documentation here on the gin-gonic website seemed to do an ok job. As I understand it, the lifecycle for middleware focusing on just the usage of context.Next() is:

  1. Request comes in
  2. Your middleware is hit
  3. context.Next() tells gin to short-circuit your middleware logic and go to the next middleware in the chain
  4. the response is sent out
  5. The logic after context.Next() is now run. Which is why in the example, the only thing that can be done is to log out how long it took to create the response. And you can't actually send out that value in the response itself.

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

3 participants