publish urls

This commit is contained in:
Mark McGranaghan 2012-10-25 21:42:49 -04:00
parent 9e8d0127d4
commit 27f79cd6cb
3 changed files with 36 additions and 6 deletions

View File

@ -53,7 +53,7 @@ Defer
# Elapsed Time
# Random Numbers
# Number Parsing
# URLs
URLs
SHA1 Hashes
Base64 Encoding
# Reading Files

View File

@ -1,3 +1,6 @@
// URLs provide a [uniform format for locating resources](...).
// Here's how to parse URLs in Go.
package main
import "fmt"
@ -5,22 +8,47 @@ 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)
}
// Access to the scheme is straightforward.
fmt.Println(u.Scheme)
// `User` contains all authentication info; call
// `Username` and `Password` on this for individual
// 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. `Split` the `Host` manually to extract
// the port.
fmt.Println(u.Host)
split := strings.Split(u.Host, ":")
fmt.Println(split[0])
fmt.Println(split[1])
h := strings.Split(u.Host, ":")
fmt.Println(h[0])
fmt.Println(h[1])
// 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)

View File

@ -1,4 +1,6 @@
$ go run urls.go
# Running our URL parsing program shows all the different
# pieces that we extracted.
$ go run urls.go
postgres
user:pass
user
@ -7,7 +9,7 @@ host.com:5432
host.com
5432
/path
frag
f
k=v
map[k:[v]]
v