net/url package: strip query from url

I am not sure if this is what you are asking but you can use the u.Path attribute to get the path of the url or any of the attributes specified by URL

type URL struct {
    Scheme   string
    Opaque   string    // encoded opaque data
    User     *Userinfo // username and password information
    Host     string    // host or host:port
    Path     string
    RawQuery string // encoded query values, without '?'
    Fragment string // fragment for references, without '#'
}
// scheme://[userinfo@]host/path[?query][#fragment]

Example:

 package main

import (
    "fmt"
    "net/url"
)

func main() {
    u, _ := url.Parse("http://www.test.com/url?foo=bar&foo=baz#this_is_fragment")
    fmt.Println("full uri:", u.String())
    fmt.Println("scheme:", u.Scheme)
    fmt.Println("opaque:", u.Opaque)
    fmt.Println("Host:", u.Host)
    fmt.Println("Path", u.Path)
    fmt.Println("Fragment", u.Fragment)
    fmt.Println("RawQuery", u.RawQuery)
    fmt.Printf("query: %#v", u.Query())
}

http://play.golang.org/p/mijE73rUgw


Yes. In case you need to get url without the query part (and without fragment/anchor) you can simply overwrite them, set to an empty string:

package main

import (
    "fmt"
    "net/url"
)

func main() {
    u, _ := url.Parse("/url?foo=bar&foo=baz")
    fmt.Printf("full uri: %#v\n", u.String())
    fmt.Printf("query: %#v", u.Query())

    u.RawQuery = ""
    u.Fragment = ""

    fmt.Println("result url:", u.String())
}

https://play.golang.org/p/RY4vlfjj3_5

In comparison to using only u.Host + u.Path or u.Path in this case you will keep the rest of the url: protocol, username and password, host.

Tags:

Go