How do I represent a path without query string?
Eg.:
www.example.com/userinstead ofwww.example.com/user?id=1
The following code didn't work:
Go:
if r.URL.Path[4:] != "" {
//do something
}
func main() {
req, err := http.NewRequest("GET", "http://www.example.com/user?id=1", nil)
if err != nil {
log.Fatal(err)
}
// get host
fmt.Printf("%v\n", req.Host) // Output: www.example.com
// path without query string
fmt.Printf("%v\n", req.URL.Path) // Output: /user
// get query string value by key
fmt.Printf("%v\n", req.URL.Query().Get("id")) // Output: 1
// raw query string
fmt.Printf("%v\n", req.URL.RawQuery) // Output: id=1
}
Go play
To add parameters to an url, you would use Values().
That means, an URL without any parameters would have its 'Values' length set to 0:
if len(r.URL.Query()) == 0 {
}
That should be the same as the r.URL.RawQuery suggested by Dewy Broto in the comments:
if r.URL.RawQuery == "" {
}
Or you can check for the presence if the key 'id' in the Values() map.
if r.URL.Query().Get("id") == "" {
//do something here
}
r.URL.Values(), to see if that works better?URL.Query (golang.org/pkg/net/url/#URL.Query) does return Values, on which you can try Get("id")