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