bihire boris
bihire boris

Reputation: 1682

How to share variables between middlewares in go-gin

For example in ExpressJS I'd have route looking like this

router.patch('/:id/approve', AuthMiddleware.verifyToken,
   AuthMiddleware.isSuperAdmin, AccommodationMiddleware.param, Accommodation.accommodationApprove);

and I'd make a variable global and access it evrywhere like req.somevariable = somevariable

is this possible in go-gin,then how to? I need to pass data across middlewares and I have no idea on how to

Upvotes: 1

Views: 4889

Answers (1)

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

You can use Context for this kind of things, here is an example:

package main

import (
    "log"
    "net/http"

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

type ParamsOne struct {
    Username string `json:"username"`
}

type ParamsTwo struct {
    Username string `json:"username"`
}

func first(c *gin.Context) {
    c.Set("variable", "foo")
    c.Next()
}

func second(c *gin.Context) {
    v := c.MustGet("variable")
    log.Printf("in middleware %s", v)
    c.Next()
}

func main() {
    r := gin.New()
    r.Use(first)
    r.Use(second)
    r.POST("/", func(c *gin.Context) {
        var f ParamsOne
        if err := c.ShouldBindBodyWith(&f, binding.JSON); err != nil {
            log.Printf("%+v", err)
        }
        log.Printf("%+v", f)
        var ff ParamsTwo
        if err := c.ShouldBindBodyWith(&ff, binding.JSON); err != nil {
            log.Printf("%+v", err)
        }
        log.Printf("%+v", ff)
        v := c.MustGet("variable")
        log.Printf("in route %s", v)
        c.IndentedJSON(http.StatusOK, f)
    })
    r.Run(":4000")
}

Output:

example$ ./example
[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] POST   /                         --> main.main.func1 (3 handlers)
[GIN-debug] Listening and serving HTTP on :4000
2020/07/05 13:11:06 in middleware foo
2020/07/05 13:11:06 {Username:somename}
2020/07/05 13:11:06 {Username:somename}
2020/07/05 13:11:06 in route foo

Upvotes: 10

Related Questions