3

How do I represent a path without query string?

Eg.:

  • www.example.com/user instead of
  • www.example.com/user?id=1

The following code didn't work:

Go:

if r.URL.Path[4:] != "" {
    //do something
}

2 Answers 2

8
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

Sign up to request clarification or add additional context in comments.

Comments

0

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
}

7 Comments

I used a simpler r.URL.Query() which gives me a map. However, if r.URL.Query != nil didn't work.
@user3918985 did you try r.URL.Values(), to see if that works better?
yup, I get this error: r.URL.Values undefined (type *url.URL has no field or method Values)
same error. I removed Values and it somehow still didn't register.
@user3918985 but at least, it does compile, right? I mean URL.Query (golang.org/pkg/net/url/#URL.Query) does return Values, on which you can try Get("id")
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.