github.com/gocuntian/go@v0.0.0-20160610041250-fee02d270bf8/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 "fmt" 9 "log" 10 "net/http" 11 "net/http/httputil" 12 "net/url" 13 "strings" 14 ) 15 16 func ExampleValues() { 17 v := url.Values{} 18 v.Set("name", "Ava") 19 v.Add("friend", "Jess") 20 v.Add("friend", "Sarah") 21 v.Add("friend", "Zoe") 22 // v.Encode() == "name=Ava&friend=Jess&friend=Sarah&friend=Zoe" 23 fmt.Println(v.Get("name")) 24 fmt.Println(v.Get("friend")) 25 fmt.Println(v["friend"]) 26 // Output: 27 // Ava 28 // Jess 29 // [Jess Sarah Zoe] 30 } 31 32 func ExampleURL() { 33 u, err := url.Parse("http://bing.com/search?q=dotnet") 34 if err != nil { 35 log.Fatal(err) 36 } 37 u.Scheme = "https" 38 u.Host = "google.com" 39 q := u.Query() 40 q.Set("q", "golang") 41 u.RawQuery = q.Encode() 42 fmt.Println(u) 43 // Output: https://google.com/search?q=golang 44 } 45 46 func ExampleURL_roundtrip() { 47 // Parse + String preserve the original encoding. 48 u, err := url.Parse("https://example.com/foo%2fbar") 49 if err != nil { 50 log.Fatal(err) 51 } 52 fmt.Println(u.Path) 53 fmt.Println(u.RawPath) 54 fmt.Println(u.String()) 55 // Output: 56 // /foo/bar 57 // /foo%2fbar 58 // https://example.com/foo%2fbar 59 } 60 61 func ExampleURL_opaque() { 62 // Sending a literal '%' in an HTTP request's Path 63 req := &http.Request{ 64 Method: "GET", 65 Host: "example.com", // takes precedence over URL.Host 66 URL: &url.URL{ 67 Host: "ignored", 68 Scheme: "https", 69 Opaque: "/%2f/", 70 }, 71 Header: http.Header{ 72 "User-Agent": {"godoc-example/0.1"}, 73 }, 74 } 75 out, err := httputil.DumpRequestOut(req, true) 76 if err != nil { 77 log.Fatal(err) 78 } 79 fmt.Println(strings.Replace(string(out), "\r", "", -1)) 80 // Output: 81 // GET /%2f/ HTTP/1.1 82 // Host: example.com 83 // User-Agent: godoc-example/0.1 84 // Accept-Encoding: gzip 85 // 86 } 87 88 func ExampleURL_ResolveReference() { 89 u, err := url.Parse("../../..//search?q=dotnet") 90 if err != nil { 91 log.Fatal(err) 92 } 93 base, err := url.Parse("http://example.com/directory/") 94 if err != nil { 95 log.Fatal(err) 96 } 97 fmt.Println(base.ResolveReference(u)) 98 // Output: 99 // http://example.com/search?q=dotnet 100 }