20

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?

5
  • 1
    mux.Vars is for named parameters from your route.
    – zerkms
    Sep 5, 2017 at 1:27
  • Thanks. Is there some provision for handling optional parameters? Sep 5, 2017 at 2:18
  • 4
    r.URL.Query().Get("param1")?
    – zerkms
    Sep 5, 2017 at 2:43
  • 2
    Ah. Of course. So the basic answer is, that's not what mux is for; use the standard way of dealing with query variables. Sep 5, 2017 at 12:03
  • 1
    @ScottDeerwester maybe add this as an answer?
    – Marek
    Jan 14, 2019 at 10:23

2 Answers 2

42

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")
-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)
}
1
  • The question is about query string and not path params Dec 4, 2022 at 17:56

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.