Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

net/url package: strip query from url

Tags:

go

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

like image 679
kwolfe Avatar asked May 29 '14 19:05

kwolfe


1 Answers

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

like image 150
fabrizioM Avatar answered Oct 16 '22 19:10

fabrizioM