github.com/tidwall/go@v0.0.0-20170415222209-6694a6888b7d/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 toJSON(m interface{}) string {
    85  	js, err := json.Marshal(m)
    86  	if err != nil {
    87  		log.Fatal(err)
    88  	}
    89  	return strings.Replace(string(js), ",", ", ", -1)
    90  }