kwolfe
kwolfe

Reputation: 1683

net/url package: strip query from url

I just wanted to make sure I wasn't missing something on the net/url package. Is there a way to get the url without the query, without using using the strings package to strip it out?

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())
}

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

Upvotes: 8

Views: 16862

Answers (3)

Nik
Nik

Reputation: 3215

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.

Upvotes: 7

fabmilo
fabmilo

Reputation: 48310

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

Upvotes: 10

julienc
julienc

Reputation: 20305

Actually you can! The URL type is defined this way:

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]

So you can use:

u, _ := url.Parse()
result := u.Host + u.Path

Upvotes: 3

Related Questions