Home > Blockchain >  Golang: Gin router with map is picking only one handler
Golang: Gin router with map is picking only one handler

Time:11-25

package main

import (
    "fmt"

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

func main() {
    server := gin.Default()

    funcs := map[string]func(string){
        "func2": func2,
        "func1": func1,
    }

    for k, v := range funcs {
        server.GET(k, func(ctx *gin.Context) {
            v(k)
        })
    }

    server.Run("127.0.0.1:8879")
}

func func1(name string) {
    fmt.Println("func1", name)
}

func func2(name string) {
    fmt.Println("func2", name)
}

Please consider this code, here I have a map to functions. Now when running this is gin router.

[GIN-debug] GET    /func2                    --> main.main.func1 (3 handlers)
[GIN-debug] GET    /func1                    --> main.main.func1 (3 handlers)

Now, no matter if is make request with func1 for func2, I am only getting one function called. Any idea, why this happening and how to fix this.

Note: I have to pass the key from map to func

CodePudding user response:

Loop variables are overwritten at each iteration, so all handlers are using the last copy of v and k. You can fix by creating copies:

 for k, v := range funcs {
        k:=k
        v:=v
        server.GET(k, func(ctx *gin.Context) {
            v(k)
        })
    }
  • Related