25

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. Commented Sep 5, 2017 at 1:27
  • Thanks. Is there some provision for handling optional parameters? Commented Sep 5, 2017 at 2:18
  • 4
    r.URL.Query().Get("param1")? Commented 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. Commented Sep 5, 2017 at 12:03
  • 1
    @ScottDeerwester maybe add this as an answer? Commented Jan 14, 2019 at 10:23

2 Answers 2

55

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") 
Sign up to request clarification or add additional context in comments.

Comments

-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 Comment

The question is about query string and not path params

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.