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