github.com/zebozhuang/go@v0.0.0-20200207033046-f8a98f6f5c5d/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/url" 12 "strings" 13 ) 14 15 func ExampleValues() { 16 v := url.Values{} 17 v.Set("name", "Ava") 18 v.Add("friend", "Jess") 19 v.Add("friend", "Sarah") 20 v.Add("friend", "Zoe") 21 // v.Encode() == "name=Ava&friend=Jess&friend=Sarah&friend=Zoe" 22 fmt.Println(v.Get("name")) 23 fmt.Println(v.Get("friend")) 24 fmt.Println(v["friend"]) 25 // Output: 26 // Ava 27 // Jess 28 // [Jess Sarah Zoe] 29 } 30 31 func ExampleURL() { 32 u, err := url.Parse("http://bing.com/search?q=dotnet") 33 if err != nil { 34 log.Fatal(err) 35 } 36 u.Scheme = "https" 37 u.Host = "google.com" 38 q := u.Query() 39 q.Set("q", "golang") 40 u.RawQuery = q.Encode() 41 fmt.Println(u) 42 // Output: https://google.com/search?q=golang 43 } 44 45 func ExampleURL_roundtrip() { 46 // Parse + String preserve the original encoding. 47 u, err := url.Parse("https://example.com/foo%2fbar") 48 if err != nil { 49 log.Fatal(err) 50 } 51 fmt.Println(u.Path) 52 fmt.Println(u.RawPath) 53 fmt.Println(u.String()) 54 // Output: 55 // /foo/bar 56 // /foo%2fbar 57 // https://example.com/foo%2fbar 58 } 59 60 func ExampleURL_ResolveReference() { 61 u, err := url.Parse("../../..//search?q=dotnet") 62 if err != nil { 63 log.Fatal(err) 64 } 65 base, err := url.Parse("http://example.com/directory/") 66 if err != nil { 67 log.Fatal(err) 68 } 69 fmt.Println(base.ResolveReference(u)) 70 // Output: 71 // http://example.com/search?q=dotnet 72 } 73 74 func ExampleParseQuery() { 75 m, err := url.ParseQuery(`x=1&y=2&y=3;z`) 76 if err != nil { 77 log.Fatal(err) 78 } 79 fmt.Println(toJSON(m)) 80 // Output: 81 // {"x":["1"], "y":["2", "3"], "z":[""]} 82 } 83 84 func ExampleURL_Hostname() { 85 u, err := url.Parse("https://example.org:8000/path") 86 if err != nil { 87 log.Fatal(err) 88 } 89 fmt.Println(u.Hostname()) 90 u, err = url.Parse("https://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:17000") 91 if err != nil { 92 log.Fatal(err) 93 } 94 fmt.Println(u.Hostname()) 95 // Output: 96 // example.org 97 // 2001:0db8:85a3:0000:0000:8a2e:0370:7334 98 } 99 100 func ExampleURL_RequestURI() { 101 u, err := url.Parse("https://example.org/path?foo=bar") 102 if err != nil { 103 log.Fatal(err) 104 } 105 fmt.Println(u.RequestURI()) 106 // Output: /path?foo=bar 107 } 108 109 func toJSON(m interface{}) string { 110 js, err := json.Marshal(m) 111 if err != nil { 112 log.Fatal(err) 113 } 114 return strings.Replace(string(js), ",", ", ", -1) 115 }