gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/gmhttp/example_test.go (about) 1 // Copyright 2012 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 gmhttp_test 6 7 import ( 8 "context" 9 "fmt" 10 "io" 11 "log" 12 "net" 13 "os" 14 "os/signal" 15 16 http "gitee.com/ks-custle/core-gm/gmhttp" 17 ) 18 19 func ExampleHijacker() { 20 http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) { 21 hj, ok := w.(http.Hijacker) 22 if !ok { 23 http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError) 24 return 25 } 26 conn, bufrw, err := hj.Hijack() 27 if err != nil { 28 http.Error(w, err.Error(), http.StatusInternalServerError) 29 return 30 } 31 // Don't forget to close the connection: 32 defer func(conn net.Conn) { 33 _ = conn.Close() 34 }(conn) 35 _, _ = bufrw.WriteString("Now we're speaking raw TCP. Say hi: ") 36 _ = bufrw.Flush() 37 s, err := bufrw.ReadString('\n') 38 if err != nil { 39 log.Printf("error reading string: %v", err) 40 return 41 } 42 _, _ = fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s) 43 _ = bufrw.Flush() 44 }) 45 } 46 47 func ExampleGet() { 48 //goland:noinspection HttpUrlsUsage 49 res, err := http.Get("http://www.google.com/robots.txt") 50 if err != nil { 51 log.Fatal(err) 52 } 53 body, err := io.ReadAll(res.Body) 54 _ = res.Body.Close() 55 if res.StatusCode > 299 { 56 log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body) 57 } 58 if err != nil { 59 log.Fatal(err) 60 } 61 fmt.Printf("%s", body) 62 } 63 64 func ExampleFileServer() { 65 // Simple static webserver: 66 log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc")))) 67 } 68 69 func ExampleFileServer_stripPrefix() { 70 // To serve a directory on disk (/tmp) under an alternate URL 71 // path (/tmpfiles/), use StripPrefix to modify the request 72 // URL's path before the FileServer sees it: 73 http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp")))) 74 } 75 76 func ExampleStripPrefix() { 77 // To serve a directory on disk (/tmp) under an alternate URL 78 // path (/tmpfiles/), use StripPrefix to modify the request 79 // URL's path before the FileServer sees it: 80 http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp")))) 81 } 82 83 type apiHandler struct{} 84 85 func (apiHandler) ServeHTTP(http.ResponseWriter, *http.Request) {} 86 87 func ExampleServeMux_Handle() { 88 mux := http.NewServeMux() 89 mux.Handle("/api/", apiHandler{}) 90 mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { 91 // The "/" pattern matches everything, so we need to check 92 // that we're at the root here. 93 if req.URL.Path != "/" { 94 http.NotFound(w, req) 95 return 96 } 97 _, _ = fmt.Fprintf(w, "Welcome to the home page!") 98 }) 99 } 100 101 // HTTP Trailers are a set of key/value pairs like headers that come 102 // after the HTTP response, instead of before. 103 func ExampleResponseWriter_trailers() { 104 mux := http.NewServeMux() 105 mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) { 106 // Before any call to WriteHeader or Write, declare 107 // the trailers you will set during the HTTP 108 // response. These three headers are actually sent in 109 // the trailer. 110 w.Header().Set("Trailer", "AtEnd1, AtEnd2") 111 w.Header().Add("Trailer", "AtEnd3") 112 113 w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header 114 w.WriteHeader(http.StatusOK) 115 116 w.Header().Set("AtEnd1", "value 1") 117 _, _ = io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n") 118 w.Header().Set("AtEnd2", "value 2") 119 w.Header().Set("AtEnd3", "value 3") // These will appear as trailers. 120 }) 121 } 122 123 func ExampleServer_Shutdown() { 124 var srv http.Server 125 126 idleConnsClosed := make(chan struct{}) 127 go func() { 128 sigint := make(chan os.Signal, 1) 129 signal.Notify(sigint, os.Interrupt) 130 <-sigint 131 132 // We received an interrupt signal, shut down. 133 if err := srv.Shutdown(context.Background()); err != nil { 134 // Error from closing listeners, or context timeout: 135 log.Printf("HTTP server Shutdown: %v", err) 136 } 137 close(idleConnsClosed) 138 }() 139 140 if err := srv.ListenAndServe(); err != http.ErrServerClosed { 141 // Error starting or closing listener: 142 log.Fatalf("HTTP server ListenAndServe: %v", err) 143 } 144 145 <-idleConnsClosed 146 } 147 148 func ExampleListenAndServeTLS() { 149 http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { 150 _, _ = io.WriteString(w, "Hello, TLS!\n") 151 }) 152 153 // One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem. 154 log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/") 155 err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil) 156 log.Fatal(err) 157 } 158 159 func ExampleListenAndServe() { 160 // Hello world, the web server 161 162 helloHandler := func(w http.ResponseWriter, req *http.Request) { 163 _, _ = io.WriteString(w, "Hello, world!\n") 164 } 165 166 http.HandleFunc("/hello", helloHandler) 167 log.Fatal(http.ListenAndServe(":8080", nil)) 168 } 169 170 func ExampleHandleFunc() { 171 h1 := func(w http.ResponseWriter, _ *http.Request) { 172 _, _ = io.WriteString(w, "Hello from a HandleFunc #1!\n") 173 } 174 h2 := func(w http.ResponseWriter, _ *http.Request) { 175 _, _ = io.WriteString(w, "Hello from a HandleFunc #2!\n") 176 } 177 178 http.HandleFunc("/", h1) 179 http.HandleFunc("/endpoint", h2) 180 181 log.Fatal(http.ListenAndServe(":8080", nil)) 182 } 183 184 func newPeopleHandler() http.Handler { 185 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 186 _, _ = fmt.Fprintln(w, "This is the people handler.") 187 }) 188 } 189 190 func ExampleNotFoundHandler() { 191 mux := http.NewServeMux() 192 193 // Create sample handler to returns 404 194 mux.Handle("/resources", http.NotFoundHandler()) 195 196 // Create sample handler that returns 200 197 mux.Handle("/resources/people/", newPeopleHandler()) 198 199 log.Fatal(http.ListenAndServe(":8080", mux)) 200 }