When you enter a URL like somedomain.com/products?type=model , you are specifying a query string, not a variable.
Query strings in Go are accessible through r.URL.Query - for example,
vals := r.URL.Query() // Returns a url.Values, which is a map[string][]string productTypes, ok := vals["type"] // Note type, not ID. ID wasn't specified anywhere. var pt string if ok { if len(productTypes) >= 1 { pt = productTypes[0] // The first `?type=model` } }
As you can see, this can be a little awkward, as it must take into account the empty value of the map and the possibility of a URL such as somedomain.com/products?type=model&this=that&here=there&type=cat , where the key can be specified more than once .
For gorilla / mux documents, you can use route variables:
// List all products, or the latest apiProductRoute.Handle("/", handler(listProducts)).Methods("GET") // List a specific product apiProductRoute.Handle("/{id}/", handler(showProduct)).Methods("GET")
Here you can use mux.Vars :
vars := mux.Vars(request) id := vars["id"]
Hope this helps clarify. I would recommend using variables if you don't need to use query strings.
source share