From 27f79cd6cbd29682b6aa6b57a15b5a3058125ed9 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Thu, 25 Oct 2012 21:42:49 -0400 Subject: [PATCH] publish urls --- examples.txt | 2 +- examples/urls/urls.go | 34 +++++++++++++++++++++++++++++++--- examples/urls/urls.sh | 6 ++++-- 3 files changed, 36 insertions(+), 6 deletions(-) diff --git a/examples.txt b/examples.txt index 168b43a..f4a0aa1 100644 --- a/examples.txt +++ b/examples.txt @@ -53,7 +53,7 @@ Defer # Elapsed Time # Random Numbers # Number Parsing -# URLs +URLs SHA1 Hashes Base64 Encoding # Reading Files diff --git a/examples/urls/urls.go b/examples/urls/urls.go index cd5dfe2..2b39fba 100644 --- a/examples/urls/urls.go +++ b/examples/urls/urls.go @@ -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) diff --git a/examples/urls/urls.sh b/examples/urls/urls.sh index 6656766..40e7e53 100644 --- a/examples/urls/urls.sh +++ b/examples/urls/urls.sh @@ -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