How do I represent a path without query string?
Eg.:
www.example.com/user
instead ofwww.example.com/user?id=1
The following code didn't work:
Go:
if r.URL.Path[4:] != "" {
//do something
}
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
}
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
", req.Host) // Output: www.example.com
// path without query string
fmt.Printf("%v
", req.URL.Path) // Output: /user
// get query string value by key
fmt.Printf("%v
", req.URL.Query().Get("id")) // Output: 1
// raw query string
fmt.Printf("%v
", req.URL.RawQuery) // Output: id=1
}
Go play