Dynamic Routes Queries Using GO and gorilla mux

0

i'm setting up dynamic routes using gorilla mux, here's the routes.go code

type Route struct {
    Name        string
    Method      string
    Pattern     string
    Queries     []string
    HandlerFunc http.HandlerFunc
}

type Routes []Route

var vers = os.Getenv("API_VERSION")
var baseURL = "/api/" + vers + "/"

var authRoutes = Routes{
    Route{
        "GetAllUsers",
        "GET",
        baseURL + "users",
        []string{"maxperpage", "{maxperpage}", "setpage", "{setpage}"},
        ssoUserController.GetAllUsers,
    },
}

and i want to create dynamic Queries using slice like this:

func Handlers() *mux.Router {

//.....
//some code
//.....

    s := r.PathPrefix("/auth").Subrouter()
    s.Use(utils.JwtVerify)
    for _, authRoute := range authRoutes {
        var handler http.Handler
        var tamp = []string{}

        handler = authRoute.HandlerFunc
        handler = Logger(handler, authRoute.Name)
        for _, q := range authRoute.Queries {

            var addQuot = strconv.Quote(q)
            tamp = append(tamp, addQuot)

        }
        queries := strings.Join(tamp, ", ") //this code create string "maxperpage", "{maxperpage:[0-99]+}", "setpage", "{setpage:[0-99]+}"

        // fmt.Println(queries)
        s.
            Methods(authRoute.Method).
            Path(authRoute.Pattern).
            Queries(queries). // produce error panic: runtime error: invalid memory address or nil pointer dereference
            Name(authRoute.Name).
            Handler(handler)

    }

    return r
}

the code above is the router.go file it will route all the routes in routes.go file and when i put the queries slice it produce error

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x20 pc=0x77a750] 

please help to put dynamic url queries using gorilla mux

go
asked on Stack Overflow Sep 13, 2019 by Ponco Herbowo • edited Sep 13, 2019 by Ponco Herbowo

1 Answer

0

You're using Queries() wrong. It gets pairs of strings, not a single string. Using Queries(authRoute.Queries...) should work.

answered on Stack Overflow Sep 13, 2019 by Burak Serdar

User contributions licensed under CC BY-SA 3.0