gin-gonic / examples

A repository to host examples and tutorials for Gin.
https://gin-gonic.com/docs/
MIT License
3.67k stars 641 forks source link

How can i add or remove middleware after gin server started dynamically? #131

Closed snowdream closed 4 months ago

snowdream commented 1 year ago

For Example:

can i add or remove middleware after gin server started dynamically? (after r.Run())

func Logger() gin.HandlerFunc {
    return func(c *gin.Context) {
        t := time.Now()

        // Set example variable
        c.Set("example", "12345")

        // before request

        c.Next()

        // after request
        latency := time.Since(t)
        log.Print(latency)

        // access the status we are sending
        status := c.Writer.Status()
        log.Println(status)
    }
}

func main() {
    r := gin.New()
    r.Use(Logger())

    r.GET("/test", func(c *gin.Context) {
        example := c.MustGet("example").(string)

        // it would print: "12345"
        log.Println(example)
    })

    // Listen and serve on 0.0.0.0:8080
    r.Run(":8080")
}
}
appleboy commented 4 months ago

move to https://github.com/gin-gonic/gin/issues/776