gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/gmhttp/cookiejar/example_test.go (about)

     1  // Copyright 2016 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 cookiejar_test
     6  
     7  import (
     8  	"fmt"
     9  	"log"
    10  	"net/url"
    11  
    12  	http "gitee.com/ks-custle/core-gm/gmhttp"
    13  	"gitee.com/ks-custle/core-gm/gmhttp/cookiejar"
    14  	"gitee.com/ks-custle/core-gm/gmhttp/httptest"
    15  )
    16  
    17  func ExampleNew() {
    18  	// Start a server to give us cookies.
    19  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    20  		if cookie, err := r.Cookie("Flavor"); err != nil {
    21  			http.SetCookie(w, &http.Cookie{Name: "Flavor", Value: "Chocolate Chip"})
    22  		} else {
    23  			cookie.Value = "Oatmeal Raisin"
    24  			http.SetCookie(w, cookie)
    25  		}
    26  	}))
    27  	defer ts.Close()
    28  
    29  	u, err := url.Parse(ts.URL)
    30  	if err != nil {
    31  		log.Fatal(err)
    32  	}
    33  
    34  	// All users of cookiejar should import "golang.org/x/net/publicsuffix"
    35  	jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
    36  	if err != nil {
    37  		log.Fatal(err)
    38  	}
    39  
    40  	client := &http.Client{
    41  		Jar: jar,
    42  	}
    43  
    44  	if _, err = client.Get(u.String()); err != nil {
    45  		log.Fatal(err)
    46  	}
    47  
    48  	fmt.Println("After 1st request:")
    49  	for _, cookie := range jar.Cookies(u) {
    50  		fmt.Printf("  %s: %s\n", cookie.Name, cookie.Value)
    51  	}
    52  
    53  	if _, err = client.Get(u.String()); err != nil {
    54  		log.Fatal(err)
    55  	}
    56  
    57  	fmt.Println("After 2nd request:")
    58  	for _, cookie := range jar.Cookies(u) {
    59  		fmt.Printf("  %s: %s\n", cookie.Name, cookie.Value)
    60  	}
    61  	// Output:
    62  	// After 1st request:
    63  	//   Flavor: Chocolate Chip
    64  	// After 2nd request:
    65  	//   Flavor: Oatmeal Raisin
    66  }