github.com/ooni/oohttp@v0.7.2/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  	"os"
    13  	"os/signal"
    14  
    15  	http "github.com/ooni/oohttp"
    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  		// Don't forget to close the connection:
    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  	// Simple static webserver:
    62  	log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
    63  }
    64  
    65  func ExampleFileServer_stripPrefix() {
    66  	// To serve a directory on disk (/tmp) under an alternate URL
    67  	// path (/tmpfiles/), use StripPrefix to modify the request
    68  	// URL's path before the FileServer sees it:
    69  	http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
    70  }
    71  
    72  func ExampleStripPrefix() {
    73  	// To serve a directory on disk (/tmp) under an alternate URL
    74  	// path (/tmpfiles/), use StripPrefix to modify the request
    75  	// URL's path before the FileServer sees it:
    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  		// The "/" pattern matches everything, so we need to check
    88  		// that we're at the root here.
    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  // HTTP Trailers are a set of key/value pairs like headers that come
    98  // after the HTTP response, instead of before.
    99  func ExampleResponseWriter_trailers() {
   100  	mux := http.NewServeMux()
   101  	mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
   102  		// Before any call to WriteHeader or Write, declare
   103  		// the trailers you will set during the HTTP
   104  		// response. These three headers are actually sent in
   105  		// the trailer.
   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") // normal header
   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") // These will appear as trailers.
   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  		// We received an interrupt signal, shut down.
   129  		if err := srv.Shutdown(context.Background()); err != nil {
   130  			// Error from closing listeners, or context timeout:
   131  			log.Printf("HTTP server Shutdown: %v", err)
   132  		}
   133  		close(idleConnsClosed)
   134  	}()
   135  
   136  	if err := srv.ListenAndServe(); err != http.ErrServerClosed {
   137  		// Error starting or closing listener:
   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  	// One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
   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  	// Hello world, the web server
   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  	// Create sample handler to returns 404
   190  	mux.Handle("/resources", http.NotFoundHandler())
   191  
   192  	// Create sample handler that returns 200
   193  	mux.Handle("/resources/people/", newPeopleHandler())
   194  
   195  	log.Fatal(http.ListenAndServe(":8080", mux))
   196  }