How can I pass a var between routes funcs and change it in every controller?

拥有回忆 提交于 2020-06-23 18:04:49

问题


I want to pass var and change it globally in every controller between routes so if controller1 change var to "as" I want controller2 to use the new value of the var = "as". How can I do it? something like this

main.go:

var test []string

func NewRouter() *gin.Engine {
    gin.SetMode(gin.ReleaseMode)
    r := gin.New()
    r.GET("/ping", gets(test))
    r.Run(":6030")
    return r
}

controller.go:

func gets(test) gin.HandlerFunc {
   fn := func(c *gin.Context){
               // Here I want to change my var (test) and I want to change it globally so if any another function use it I want to use the new value I just change it here
         }
}

回答1:


The comment of mkopriva already give you a solution on how to using mutex.

However, since golang promote share memory by communicating, I propose another solution using channel.

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
)

func main() {
  r := NewRouter()
  r.Run(":6030")
}

var test = []string{"abc"}

func NewRouter() *gin.Engine {
    gin.SetMode(gin.ReleaseMode)
    r := gin.New()

    updateChan := make(chan []string, 0)
    r.GET("/", gets(updateChan))
    r.GET("/mn", er(updateChan))
    return r
}

func gets(updateChan chan []string) gin.HandlerFunc {
    return func(c *gin.Context){
        fmt.Println("before update in get, test=",test)
        newTest := []string{"def"}
        updateChan <- newTest
  }

}

func er(updateChan chan []string) gin.HandlerFunc {
    return func(c *gin.Context){
        test = <-updateChan
        fmt.Println("get a new value for test in er, test=",test)

  }

}

With an unbuffered channel updateChan, test will always be update with the latest input pushed to updateChan channel. And no data race will happen here.

Of course this is just a simple demonstration and there are lot more stuff to make a complete HTTP server with gin. But I limit the scope of the demonstration to channel usage only.



来源:https://stackoverflow.com/questions/61968405/how-can-i-pass-a-var-between-routes-funcs-and-change-it-in-every-controller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!