...

Source file src/net/http/cookiejar/example_test.go

Documentation: net/http/cookiejar

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

View as plain text