These are chat archives for gin-gonic/gin

12th
Jan 2017
nolka
@nolka
Jan 12 2017 08:17
@javierprovecho My solution is inject channel to context use middleware)
It looks good)
Javier Provecho Fernandez
@javierprovecho
Jan 12 2017 08:20
@nolka using Keys? That's going to be pretty expensive for one key that it's constant. Think that when you set up the first key in a context, you are initializing and allocating a map. I suggest to pass it with a first class function.
nolka
@nolka
Jan 12 2017 08:23
@javierprovecho
func AppCommandsMiddleware(req chan structs.AppMessage) gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Set("appRequests", req)
        c.Next()
    }
}
///...
func (a *WebApp) Start(req chan structs.AppMessage) {
    fmt.Printf("Statring server at %s:%d", a.Host, a.Port)
    gin := gin.Default()
    gin.Use(AppCommandsMiddleware(req))
        ////
}
Something like this)
Javier Provecho Fernandez
@javierprovecho
Jan 12 2017 08:25
@nolka make the same but directly with the handlers

(can't type snippet on mobile)
nolka
@nolka
Jan 12 2017 08:25
I'm too nooob to do this)
Javier Provecho Fernandez
@javierprovecho
Jan 12 2017 08:26
func myHander(a chan string) func (c *gin.Context) {
return func (c *gin.Context) {
// Your logic, you can use your channel 'a'
}
}
@nolka sorry for indentation, you get the idea?
It's almost the same as you wrote before, but without middleware and key maps
Directly onto the handler
nolka
@nolka
Jan 12 2017 08:32
I think, i need to explore your example deeper) I do not have enough knowledge of the golang)
@javierprovecho thanks for your response)
Javier Provecho Fernandez
@javierprovecho
Jan 12 2017 08:34
@nolka I'll write you a full example later when I get a real keyboard
nolka
@nolka
Jan 12 2017 08:35
@javierprovecho ok, thanks, i will wait)
Javier Provecho Fernandez
@javierprovecho
Jan 12 2017 10:04
@nolka

// func that return handler
func myHandlerA(a chan string) func (c *gin.Context) {
    return func (c *gin.Context) {
        c.JSON(200, gin.H{"status":"ok"})
        a <- c.ClientIP()
    }
}

// handler
func myHandlerB(c *gin.Context) {
    // do something
}

func main() {
    r := gin.Default()
    myChan := make(chan string)

    r.GET("/send-my-ip", myHandlerA(myChan))
    r.GET("/something", myHandlerB)
    r.Run()
}