github.com/guyezi/gofrontend@v0.0.0-20200228202240-7a62a49e62c0/libgo/go/net/http/httptest/example_test.go (about) 1 // Copyright 2013 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 httptest_test 6 7 import ( 8 "fmt" 9 "io" 10 "io/ioutil" 11 "log" 12 "net/http" 13 "net/http/httptest" 14 ) 15 16 func ExampleResponseRecorder() { 17 handler := func(w http.ResponseWriter, r *http.Request) { 18 io.WriteString(w, "<html><body>Hello World!</body></html>") 19 } 20 21 req := httptest.NewRequest("GET", "http://example.com/foo", nil) 22 w := httptest.NewRecorder() 23 handler(w, req) 24 25 resp := w.Result() 26 body, _ := ioutil.ReadAll(resp.Body) 27 28 fmt.Println(resp.StatusCode) 29 fmt.Println(resp.Header.Get("Content-Type")) 30 fmt.Println(string(body)) 31 32 // Output: 33 // 200 34 // text/html; charset=utf-8 35 // <html><body>Hello World!</body></html> 36 } 37 38 func ExampleServer() { 39 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 40 fmt.Fprintln(w, "Hello, client") 41 })) 42 defer ts.Close() 43 44 res, err := http.Get(ts.URL) 45 if err != nil { 46 log.Fatal(err) 47 } 48 greeting, err := ioutil.ReadAll(res.Body) 49 res.Body.Close() 50 if err != nil { 51 log.Fatal(err) 52 } 53 54 fmt.Printf("%s", greeting) 55 // Output: Hello, client 56 } 57 58 func ExampleServer_hTTP2() { 59 ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 60 fmt.Fprintf(w, "Hello, %s", r.Proto) 61 })) 62 ts.EnableHTTP2 = true 63 ts.StartTLS() 64 defer ts.Close() 65 66 res, err := ts.Client().Get(ts.URL) 67 if err != nil { 68 log.Fatal(err) 69 } 70 greeting, err := ioutil.ReadAll(res.Body) 71 res.Body.Close() 72 if err != nil { 73 log.Fatal(err) 74 } 75 fmt.Printf("%s", greeting) 76 77 // Output: Hello, HTTP/2.0 78 } 79 80 func ExampleNewTLSServer() { 81 ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 82 fmt.Fprintln(w, "Hello, client") 83 })) 84 defer ts.Close() 85 86 client := ts.Client() 87 res, err := client.Get(ts.URL) 88 if err != nil { 89 log.Fatal(err) 90 } 91 92 greeting, err := ioutil.ReadAll(res.Body) 93 res.Body.Close() 94 if err != nil { 95 log.Fatal(err) 96 } 97 98 fmt.Printf("%s", greeting) 99 // Output: Hello, client 100 }