github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/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  	"fmt"
     9  	"io"
    10  	"io/ioutil"
    11  	"log"
    12  	"net/http"
    13  )
    14  
    15  func ExampleHijacker() {
    16  	http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
    17  		hj, ok := w.(http.Hijacker)
    18  		if !ok {
    19  			http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
    20  			return
    21  		}
    22  		conn, bufrw, err := hj.Hijack()
    23  		if err != nil {
    24  			http.Error(w, err.Error(), http.StatusInternalServerError)
    25  			return
    26  		}
    27  		// Don't forget to close the connection:
    28  		defer conn.Close()
    29  		bufrw.WriteString("Now we're speaking raw TCP. Say hi: ")
    30  		bufrw.Flush()
    31  		s, err := bufrw.ReadString('\n')
    32  		if err != nil {
    33  			log.Printf("error reading string: %v", err)
    34  			return
    35  		}
    36  		fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s)
    37  		bufrw.Flush()
    38  	})
    39  }
    40  
    41  func ExampleGet() {
    42  	res, err := http.Get("http://www.google.com/robots.txt")
    43  	if err != nil {
    44  		log.Fatal(err)
    45  	}
    46  	robots, err := ioutil.ReadAll(res.Body)
    47  	res.Body.Close()
    48  	if err != nil {
    49  		log.Fatal(err)
    50  	}
    51  	fmt.Printf("%s", robots)
    52  }
    53  
    54  func ExampleFileServer() {
    55  	// Simple static webserver:
    56  	log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
    57  }
    58  
    59  func ExampleFileServer_stripPrefix() {
    60  	// To serve a directory on disk (/tmp) under an alternate URL
    61  	// path (/tmpfiles/), use StripPrefix to modify the request
    62  	// URL's path before the FileServer sees it:
    63  	http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
    64  }
    65  
    66  func ExampleStripPrefix() {
    67  	// To serve a directory on disk (/tmp) under an alternate URL
    68  	// path (/tmpfiles/), use StripPrefix to modify the request
    69  	// URL's path before the FileServer sees it:
    70  	http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
    71  }
    72  
    73  type apiHandler struct{}
    74  
    75  func (apiHandler) ServeHTTP(http.ResponseWriter, *http.Request) {}
    76  
    77  func ExampleServeMux_Handle() {
    78  	mux := http.NewServeMux()
    79  	mux.Handle("/api/", apiHandler{})
    80  	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    81  		// The "/" pattern matches everything, so we need to check
    82  		// that we're at the root here.
    83  		if req.URL.Path != "/" {
    84  			http.NotFound(w, req)
    85  			return
    86  		}
    87  		fmt.Fprintf(w, "Welcome to the home page!")
    88  	})
    89  }
    90  
    91  // HTTP Trailers are a set of key/value pairs like headers that come
    92  // after the HTTP response, instead of before.
    93  func ExampleResponseWriter_trailers() {
    94  	mux := http.NewServeMux()
    95  	mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
    96  		// Before any call to WriteHeader or Write, declare
    97  		// the trailers you will set during the HTTP
    98  		// response. These three headers are actually sent in
    99  		// the trailer.
   100  		w.Header().Set("Trailer", "AtEnd1, AtEnd2")
   101  		w.Header().Add("Trailer", "AtEnd3")
   102  
   103  		w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
   104  		w.WriteHeader(http.StatusOK)
   105  
   106  		w.Header().Set("AtEnd1", "value 1")
   107  		io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
   108  		w.Header().Set("AtEnd2", "value 2")
   109  		w.Header().Set("AtEnd3", "value 3") // These will appear as trailers.
   110  	})
   111  }