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

send response from middleware, continue to execute handler chain #3934

Open
daveoy opened this issue Apr 25, 2024 · 3 comments
Open

send response from middleware, continue to execute handler chain #3934

daveoy opened this issue Apr 25, 2024 · 3 comments

Comments

@daveoy
Copy link

daveoy commented Apr 25, 2024

Description

i cannot seem to send a response back to the requestor from within a middleware handler chain and continue to run handlers in the chain. everything i have tried will send the response after all handlers are complete

How to reproduce

package main

import (
	"fmt"
	"net/http"
	"time"

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

func middlewareOne() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println("middlewareOne")
	}
}
func middlewareTwo() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println("middlewareTwo")
		go func(c *gin.Context) {
			c.Next()
		}(c)
		time.Sleep(1 * time.Second) //goroutine takes a flash to get going
		c.Abort()
		c.JSON(http.StatusOK, gin.H{"message": "early response"})
	}
}
func middlewareThree() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println("middlewareThree")
	}
}
func handler() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println("handler")
	}
}
func main() {
	g := gin.Default()
	g.Use(middlewareOne(), middlewareTwo())
	g.GET("/example", handler(), middlewareThree())
	g.Run(":8080")
}

Expectations

curl:

»  curl localhost:8080/example
{"message":"early response"}%

logs:

✗  go run example.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    /example                  --> main.main.middlewareThree.func4 (6 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 :8080
middlewareOne
middlewareTwo
[GIN] 2024/04/25 - 15:09:30 | 200 |  1.000348166s |       127.0.0.1 | GET      "/example"
handler
middlewareThree

Actual result

curl:

»  curl localhost:8080/example
{"message":"early response"}%

logs:

✗  go run example.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    /example                  --> main.main.middlewareThree.func4 (6 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 :8080
middlewareOne
middlewareTwo
handler
middlewareThree
[GIN] 2024/04/25 - 15:09:30 | 200 |  1.000348166s |       127.0.0.1 | GET      "/example"

Environment

  • go version: v1.21.2
  • gin version (or commit ref): v1.9.1
  • operating system: ubuntu
@daveoy
Copy link
Author

daveoy commented Apr 25, 2024

the goal here is to return a response to a slack slash command immediately, then go off and do the work the user asked for and return those responses later via an http.Client.

things ive tried:

  • c.writer.writeheader(http.statusok)
  • c.writer.flush()
  • c.Status(http.statusaccepted)
  • using a copy of the context in the goroutine and calling Next() on that (no handler chain in copy)

middleware chaining is preferred because it simplifies the addition of new routes, all routes will be subject to the same flow (including responding quickly, then doing some async work).

@daveoy
Copy link
Author

daveoy commented Apr 26, 2024

somehow even this executes functions in the same order:

package main

import (
	"fmt"
	"net/http"

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

func middlewareOne() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println("middlewareOne")
	}
}
func middlewareTwo() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println("middlewareTwo")
		go func(ctx *gin.Context) {
			runhandlers(ctx)
		}(c)
		c.AbortWithStatusJSON(http.StatusOK, gin.H{"message": "early response"})
	}
}
func middlewareThree() func() {
	return func() {
		fmt.Println("middlewareThree")
	}
}
func handler() func() {
	return func() {
		fmt.Println("handler")
	}
}
func getmiddleware() []gin.HandlerFunc {
	return []gin.HandlerFunc{middlewareOne(), middlewareTwo()}
}
func gethandlers() []func() {
	return []func(){
		handler(),
		middlewareThree(),
	}
}
func runhandlers(c *gin.Context) {
	for _, handler := range gethandlers() {
		handler()
	}
}
func main() {
	g := gin.Default()
	g.GET("/example", getmiddleware()...)
	g.Run(":8080")
}

with and without a time.Sleep

@daveoy
Copy link
Author

daveoy commented Apr 26, 2024

so this works, though isn't ideal as we step out of gin for the bulk of the processing:

package main

import (
	"fmt"
	"net/http"
	"time"

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

func middlewareOne() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println("middlewareOne")
		c.Set("dummy_key", "dummy_value")
	}
}
func middlewareTwo() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println("middlewareTwo")
		go func(ctx *gin.Context) {
			runhandlers(ctx)
		}(c)
		c.AbortWithStatusJSON(http.StatusOK, gin.H{"message": "early response"})
	}
}
func middlewareThree(c *gin.Context) func() {
	return func() {
		fmt.Println(c.Get("dummy_key"))
		fmt.Println("middlewareThree")
	}
}
func handler(c *gin.Context) func() {
	return func() {
		fmt.Println(c.Get("dummy_key"))
		fmt.Println("handler")
	}
}
func getmiddleware() []gin.HandlerFunc {
	return []gin.HandlerFunc{middlewareOne(), middlewareTwo()}
}
func gethandlers(c *gin.Context) []func() {
	return []func(){
		handler(c),
		middlewareThree(c),
	}
}
func runhandlers(c *gin.Context) {
	for _, handler := range gethandlers(c) {
		time.Sleep(2 * time.Second)
		handler()
	}
}
func main() {
	g := gin.Default()
	g.GET("/example", getmiddleware()...)
	g.Run(":8080")
}

curl:

»  curl localhost:8080/example
{"message":"early response"}%

log:

»  go run example.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    /example                  --> main.main.getmiddleware.middlewareTwo.func2 (4 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 :8080
middlewareOne
middlewareTwo
[GIN] 2024/04/26 - 13:36:16 | 200 |       70.51µs |       127.0.0.1 | GET      "/example"
dummy_value true
handler
dummy_value true
middlewareThree

can anyone think of a better way? i would much rather wire up the middleware as in the written example in the issue

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

1 participant