-
Notifications
You must be signed in to change notification settings - Fork 7
/
url-parsing.go
45 lines (36 loc) · 1.03 KB
/
url-parsing.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import (
"fmt"
"net"
"net/url"
)
func main() {
s := "postgres://user:pass@host.com:5432/path?k=v#"
u, err := url.Parse(s)
if err != nil {
panic(err)
}
fmt.Println(u.Scheme)
fmt.Println(u.User)
fmt.Println(u.User.Username())
p, _ := u.User.Password()
fmt.Println(p)
// The Host contains both the hostname and the port, if present. Use SplitHostPort to extract them.
fmt.Println(u.Host)
host, port, _ := net.SplitHostPort(u.Host)
fmt.Println(host)
fmt.Println(port)
// Here we extract the path and the fragment after the #.
fmt.Println(u.Path)
fmt.Println(u.Fragment)
// To get query params in a string of k=v format, use RawQuery. You can also parse query params into a map. The parsed query param maps are from strings to slices of strings, so index into [0] if you only want the first value.
fmt.Println(u.RawQuery)
m, _ := url.ParseQuery(u.RawQuery)
fmt.Println(m)
fmt.Println(m["k"][0])
u2 := "https://www.google.com"
i, _ := url.Parse(u2)
fmt.Println(i)
fmt.Println(i.Scheme)
fmt.Println(i.Host)
}