github.com/dannin/go@v0.0.0-20161031215817-d35dfd405eaa/src/net/url/example_test.go (about) 1 // Copyright 2012 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package url_test 6 7 import ( 8 "encoding/json" 9 "fmt" 10 "log" 11 "net/http" 12 "net/http/httputil" 13 "net/url" 14 "strings" 15 ) 16 17 func ExampleValues() { 18 v := url.Values{} 19 v.Set("name", "Ava") 20 v.Add("friend", "Jess") 21 v.Add("friend", "Sarah") 22 v.Add("friend", "Zoe") 23 // v.Encode() == "name=Ava&friend=Jess&friend=Sarah&friend=Zoe" 24 fmt.Println(v.Get("name")) 25 fmt.Println(v.Get("friend")) 26 fmt.Println(v["friend"]) 27 // Output: 28 // Ava 29 // Jess 30 // [Jess Sarah Zoe] 31 } 32 33 func ExampleURL() { 34 u, err := url.Parse("http://bing.com/search?q=dotnet") 35 if err != nil { 36 log.Fatal(err) 37 } 38 u.Scheme = "https" 39 u.Host = "google.com" 40 q := u.Query() 41 q.Set("q", "golang") 42 u.RawQuery = q.Encode() 43 fmt.Println(u) 44 // Output: https://google.com/search?q=golang 45 } 46 47 func ExampleURL_roundtrip() { 48 // Parse + String preserve the original encoding. 49 u, err := url.Parse("https://example.com/foo%2fbar") 50 if err != nil { 51 log.Fatal(err) 52 } 53 fmt.Println(u.Path) 54 fmt.Println(u.RawPath) 55 fmt.Println(u.String()) 56 // Output: 57 // /foo/bar 58 // /foo%2fbar 59 // https://example.com/foo%2fbar 60 } 61 62 func ExampleURL_opaque() { 63 // Sending a literal '%' in an HTTP request's Path 64 req := &http.Request{ 65 Method: "GET", 66 Host: "example.com", // takes precedence over URL.Host 67 URL: &url.URL{ 68 Host: "ignored", 69 Scheme: "https", 70 Opaque: "/%2f/", 71 }, 72 Header: http.Header{ 73 "User-Agent": {"godoc-example/0.1"}, 74 }, 75 } 76 out, err := httputil.DumpRequestOut(req, true) 77 if err != nil { 78 log.Fatal(err) 79 } 80 fmt.Println(strings.Replace(string(out), "\r", "", -1)) 81 // Output: 82 // GET /%2f/ HTTP/1.1 83 // Host: example.com 84 // User-Agent: godoc-example/0.1 85 // Accept-Encoding: gzip 86 // 87 } 88 89 func ExampleURL_ResolveReference() { 90 u, err := url.Parse("../../..//search?q=dotnet") 91 if err != nil { 92 log.Fatal(err) 93 } 94 base, err := url.Parse("http://example.com/directory/") 95 if err != nil { 96 log.Fatal(err) 97 } 98 fmt.Println(base.ResolveReference(u)) 99 // Output: 100 // http://example.com/search?q=dotnet 101 } 102 103 func ExampleParseQuery() { 104 m, err := url.ParseQuery(`x=1&y=2&y=3;z`) 105 if err != nil { 106 log.Fatal(err) 107 } 108 fmt.Println(toJSON(m)) 109 // Output: 110 // {"x":["1"], "y":["2", "3"], "z":[""]} 111 } 112 113 func toJSON(m interface{}) string { 114 js, err := json.Marshal(m) 115 if err != nil { 116 log.Fatal(err) 117 } 118 return strings.Replace(string(js), ",", ", ", -1) 119 }