gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
79.11k stars 8.03k forks source link

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

Open daveoy opened 7 months ago

daveoy commented 7 months ago

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

daveoy commented 7 months ago

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:

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 commented 7 months ago

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 commented 7 months ago

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

JimChenWYU commented 3 months ago

Why you should be print this text before your handler and middlewareThree ?

image