-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurlparsing.go
61 lines (51 loc) · 1.3 KB
/
urlparsing.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"fmt"
"net"
"net/url"
)
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:[email protected]:5432/path?k=v#f"
// Parse the URL and ensure there are no errors.
u, err := url.Parse(s)
if err != nil {
panic(err)
}
// Access the scheme is straightforward.
fmt.Println(u.Scheme)
//
// User contains all authentication info; call
// Username and Password on this for indivudual
// values.
//
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 stringss to slices
// of strings, so index [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])
}