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