Retrieve optional query variables with gorilla mux?
Asked Answered
T

2

24

I'm writing a handler that can take either POST or GET. As such, I want the option of being able to say:

http://host/query?parm1=value&parm2=value

I was assuming that Gorilla mux would then give me:

{
    "parm1": "value",
    "parm2": "value
}

but mux.Vars(r) is empty. I'm aware that using .Query("key", "value" will make the parameters mandatory, which isn't what I want. What am I missing?

Typal answered 5/9, 2017 at 1:20 Comment(5)
mux.Vars is for named parameters from your route.Kalb
Thanks. Is there some provision for handling optional parameters?Typal
r.URL.Query().Get("param1")?Kalb
Ah. Of course. So the basic answer is, that's not what mux is for; use the standard way of dealing with query variables.Typal
@ScottDeerwester maybe add this as an answer?Deanadeanda
T
50

As reflected in a comment, the basic answer is "that's not what mux is for". mux is great at picking apart the path portion of a URL, and turning the components into variables. To give a hypothetical example, a call that gives information about a country might have a spec that looks like this:

country/{code}

and accept calls that look like this:

http://myhost/country/DE

You'd get the value of the code parameter like this:

code := mux.Vars(r)["code"]

If you want to pass query variables, you don't do that with mux. Just grab them straight from the request. So given the alternative query syntax:

http://myhost/country?code=DE

you'd do:

code := r.URL.Query().Get("code")
Typal answered 15/1, 2019 at 15:13 Comment(0)
L
-3

If you have an Handler function like the following, Then you can extract the Query string value (here its {param1}) using any of the two methods.

Method 1. It iterates through the query strings and prints the key and value.

Method 2. Directly extract the value using the mux Router object.

// Rounter for handling the request, Query string passed in {param1} variable

router.HandleFunc("/viewdemo/{param1}", GetDemoDetail).Methods("GET")


func GetData(response http.ResponseWriter, request *http.Request) {
// iterate throguth the object and extract key and value
    for k, v := range mux.Vars(request) {
        fmt.Printf("key=%v, value=%v", k, v)
    }

//Use the mux router to extract the value of query string {param1}
    params := mux.Vars(request)
    objid := params["param1"]
    fmt.Println("Query string key value", objid)
}
Lcm answered 7/7, 2021 at 5:1 Comment(1)
The question is about query string and not path paramsMarcheshvan

© 2022 - 2024 — McMap. All rights reserved.