URLs provide a uniform way to locate resources. Here’s how to parse URLs in Go. |
|
package main
|
|
import "fmt"
import "net/url"
import "strings"
|
|
func main() {
|
|
We’ll parse this example URL, which includes a scheme, authentication info, host, port, path, query params, and query fragment. |
s := "postgres://user:pass@host.com:5432/path?k=v#f"
|
Parse the URL and ensure there are no errors. |
u, err := url.Parse(s)
if err != nil {
panic(err)
}
|
Accessing the scheme is straightforward. |
fmt.Println(u.Scheme)
|
|
fmt.Println(u.User)
fmt.Println(u.User.Username())
p, _ := u.User.Password()
fmt.Println(p)
|
The |
fmt.Println(u.Host)
h := strings.Split(u.Host, ":")
fmt.Println(h[0])
fmt.Println(h[1])
|
Here we extract the |
fmt.Println(u.Path)
fmt.Println(u.Fragment)
|
To get query params in a string of |
fmt.Println(u.RawQuery)
m, _ := url.ParseQuery(u.RawQuery)
fmt.Println(m)
fmt.Println(m["k"][0])
}
|
Running our URL parsing program shows all the different pieces that we extracted. |
$ go run url-parsing.go
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
f
k=v
map[k:[v]]
v
|
Previous example: Number Parsing.
Next example: SHA1 Hashes.