github.com/yanyiwu/go@v0.0.0-20150106053140-03d6637dbb7f/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_opaque() {
    47  	// Sending a literal '%' in an HTTP request's Path
    48  	req := &http.Request{
    49  		Method: "GET",
    50  		Host:   "example.com", // takes precendence over URL.Host
    51  		URL: &url.URL{
    52  			Host:   "ignored",
    53  			Scheme: "https",
    54  			Opaque: "/%2f/",
    55  		},
    56  		Header: http.Header{
    57  			"User-Agent": {"godoc-example/0.1"},
    58  		},
    59  	}
    60  	out, err := httputil.DumpRequestOut(req, true)
    61  	if err != nil {
    62  		log.Fatal(err)
    63  	}
    64  	fmt.Println(strings.Replace(string(out), "\r", "", -1))
    65  	// Output:
    66  	// GET /%2f/ HTTP/1.1
    67  	// Host: example.com
    68  	// User-Agent: godoc-example/0.1
    69  	// Accept-Encoding: gzip
    70  	//
    71  }