Source file
src/net/http/example_test.go
1
2
3
4
5 package http_test
6
7 import (
8 "context"
9 "fmt"
10 "io"
11 "log"
12 "net/http"
13 "os"
14 "os/signal"
15 "time"
16 )
17
18 func ExampleHijacker() {
19 http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
20 hj, ok := w.(http.Hijacker)
21 if !ok {
22 http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
23 return
24 }
25 conn, bufrw, err := hj.Hijack()
26 if err != nil {
27 http.Error(w, err.Error(), http.StatusInternalServerError)
28 return
29 }
30
31 defer conn.Close()
32 bufrw.WriteString("Now we're speaking raw TCP. Say hi: ")
33 bufrw.Flush()
34 s, err := bufrw.ReadString('\n')
35 if err != nil {
36 log.Printf("error reading string: %v", err)
37 return
38 }
39 fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s)
40 bufrw.Flush()
41 })
42 }
43
44 func ExampleGet() {
45 res, err := http.Get("http://www.google.com/robots.txt")
46 if err != nil {
47 log.Fatal(err)
48 }
49 body, err := io.ReadAll(res.Body)
50 res.Body.Close()
51 if res.StatusCode > 299 {
52 log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body)
53 }
54 if err != nil {
55 log.Fatal(err)
56 }
57 fmt.Printf("%s", body)
58 }
59
60 func ExampleFileServer() {
61
62 log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
63 }
64
65 func ExampleFileServer_stripPrefix() {
66
67
68
69 http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
70 }
71
72 func ExampleStripPrefix() {
73
74
75
76 http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
77 }
78
79 type apiHandler struct{}
80
81 func (apiHandler) ServeHTTP(http.ResponseWriter, *http.Request) {}
82
83 func ExampleServeMux_Handle() {
84 mux := http.NewServeMux()
85 mux.Handle("/api/", apiHandler{})
86 mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
87
88
89 if req.URL.Path != "/" {
90 http.NotFound(w, req)
91 return
92 }
93 fmt.Fprintf(w, "Welcome to the home page!")
94 })
95 }
96
97
98
99 func ExampleResponseWriter_trailers() {
100 mux := http.NewServeMux()
101 mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
102
103
104
105
106 w.Header().Set("Trailer", "AtEnd1, AtEnd2")
107 w.Header().Add("Trailer", "AtEnd3")
108
109 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
110 w.WriteHeader(http.StatusOK)
111
112 w.Header().Set("AtEnd1", "value 1")
113 io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
114 w.Header().Set("AtEnd2", "value 2")
115 w.Header().Set("AtEnd3", "value 3")
116 })
117 }
118
119 func ExampleServer_Shutdown() {
120 var srv http.Server
121
122 idleConnsClosed := make(chan struct{})
123 go func() {
124 sigint := make(chan os.Signal, 1)
125 signal.Notify(sigint, os.Interrupt)
126 <-sigint
127
128
129 if err := srv.Shutdown(context.Background()); err != nil {
130
131 log.Printf("HTTP server Shutdown: %v", err)
132 }
133 close(idleConnsClosed)
134 }()
135
136 if err := srv.ListenAndServe(); err != http.ErrServerClosed {
137
138 log.Fatalf("HTTP server ListenAndServe: %v", err)
139 }
140
141 <-idleConnsClosed
142 }
143
144 func ExampleListenAndServeTLS() {
145 http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
146 io.WriteString(w, "Hello, TLS!\n")
147 })
148
149
150 log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/")
151 err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
152 log.Fatal(err)
153 }
154
155 func ExampleListenAndServe() {
156
157
158 helloHandler := func(w http.ResponseWriter, req *http.Request) {
159 io.WriteString(w, "Hello, world!\n")
160 }
161
162 http.HandleFunc("/hello", helloHandler)
163 log.Fatal(http.ListenAndServe(":8080", nil))
164 }
165
166 func ExampleHandleFunc() {
167 h1 := func(w http.ResponseWriter, _ *http.Request) {
168 io.WriteString(w, "Hello from a HandleFunc #1!\n")
169 }
170 h2 := func(w http.ResponseWriter, _ *http.Request) {
171 io.WriteString(w, "Hello from a HandleFunc #2!\n")
172 }
173
174 http.HandleFunc("/", h1)
175 http.HandleFunc("/endpoint", h2)
176
177 log.Fatal(http.ListenAndServe(":8080", nil))
178 }
179
180 func newPeopleHandler() http.Handler {
181 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
182 fmt.Fprintln(w, "This is the people handler.")
183 })
184 }
185
186 func ExampleNotFoundHandler() {
187 mux := http.NewServeMux()
188
189
190 mux.Handle("/resources", http.NotFoundHandler())
191
192
193 mux.Handle("/resources/people/", newPeopleHandler())
194
195 log.Fatal(http.ListenAndServe(":8080", mux))
196 }
197
198 func ExampleProtocols_http1() {
199 srv := http.Server{
200 Addr: ":8443",
201 }
202
203
204 srv.Protocols = new(http.Protocols)
205 srv.Protocols.SetHTTP1(true)
206
207 log.Fatal(srv.ListenAndServeTLS("cert.pem", "key.pem"))
208 }
209
210 func ExampleProtocols_http1or2() {
211 t := http.DefaultTransport.(*http.Transport).Clone()
212
213
214 t.Protocols = new(http.Protocols)
215 t.Protocols.SetHTTP1(true)
216 t.Protocols.SetHTTP2(true)
217
218 cli := &http.Client{Transport: t}
219 res, err := cli.Get("http://www.google.com/robots.txt")
220 if err != nil {
221 log.Fatal(err)
222 }
223 res.Body.Close()
224 }
225
226 func ExampleCrossOriginProtection() {
227 mux := http.NewServeMux()
228
229 mux.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request) {
230 io.WriteString(w, "request allowed\n")
231 })
232
233 srv := http.Server{
234 Addr: ":8080",
235 ReadTimeout: 15 * time.Second,
236 WriteTimeout: 15 * time.Second,
237
238
239 Handler: http.NewCrossOriginProtection().Handler(mux),
240 }
241
242 log.Fatal(srv.ListenAndServe())
243 }
244
View as plain text