Passing the Channel into a Handle Function with Context. Withvalue

I would like to use a channel for managing the global shared variables (something like: map[string]MyStruct) into my serverApp (as I know it's more "go way" rather than use sync.Mutex). I found this question (Golang handlefunc with channel) with two possible solutions. But I know it's possible to pass the channel with context.WithValue in the middleware (for necessary routes) and get access to it from the handle function if I need it? Or are there any reasons why I shouldn't do it and better use the "extend method" (from the @sberry answer) instead?

I use Echo Framework in this example:

func bindChannel(CmdChan chan CmdOp) echo.MiddlewareFunc {
    return func(next echo.HandlerFunc) echo.HandlerFunc {
        return func(c echo.Context) error {
            c.Set("cmdChan", CmdChan)
            return next(c)
        }
    }
}

var CmdChan chan CmdOp
   type CmdOp struct {
    Type            string
    Key             string
    Val             interface{}
    Resp            chan interface{}
}

func HandleFuncExmpl(c echo.Context) error {
    cmdChan := c.Get("cmdChan").(chan CmdOp)
}
2
Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article