github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/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 ExampleNewTLSServer() { 59 ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 60 fmt.Fprintln(w, "Hello, client") 61 })) 62 defer ts.Close() 63 64 client := ts.Client() 65 res, err := client.Get(ts.URL) 66 if err != nil { 67 log.Fatal(err) 68 } 69 70 greeting, err := ioutil.ReadAll(res.Body) 71 res.Body.Close() 72 if err != nil { 73 log.Fatal(err) 74 } 75 76 fmt.Printf("%s", greeting) 77 // Output: Hello, client 78 }