github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/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  	"github.com/shogo82148/std/context"
     9  	"github.com/shogo82148/std/fmt"
    10  	"github.com/shogo82148/std/io"
    11  	"github.com/shogo82148/std/log"
    12  	"github.com/shogo82148/std/net/http"
    13  	"github.com/shogo82148/std/os"
    14  	"github.com/shogo82148/std/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  		// 接続を閉じることを忘れないでください:
    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  	body, err := io.ReadAll(res.Body)
    49  	res.Body.Close()
    50  	if res.StatusCode > 299 {
    51  		log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body)
    52  	}
    53  	if err != nil {
    54  		log.Fatal(err)
    55  	}
    56  	fmt.Printf("%s", body)
    57  }
    58  
    59  func ExampleFileServer() {
    60  	// シンプルな静的 Web サーバー:
    61  	log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
    62  }
    63  
    64  func ExampleFileServer_stripPrefix() {
    65  	// ディスク上のディレクトリ (/tmp) を別の URL パス (/tmpfiles/) の下で提供するには、
    66  	// StripPrefix を使用して、FileServer がそれを見る前に
    67  	// リクエスト URL のパスを変更します。
    68  	http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
    69  }
    70  
    71  func ExampleStripPrefix() {
    72  	// ディスク上のディレクトリ (/tmp) を別の URL パス (/tmpfiles/) の下で提供するには、
    73  	// StripPrefix を使用して、FileServer がそれを見る前に
    74  	// リクエスト URL のパスを変更します。
    75  	http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
    76  }
    77  
    78  func ExampleServeMux_Handle() {
    79  	// ServeMux を作成し、"/api/" には apiHandler{} を、"/" には無名関数を割り当てます。
    80  	mux := http.NewServeMux()
    81  	mux.Handle("/api/", apiHandler{})
    82  	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    83  		// "/" パターンはすべてにマッチするため、ここでルートにいることを確認する必要があります。
    84  		if req.URL.Path != "/" {
    85  			http.NotFound(w, req)
    86  			return
    87  		}
    88  		fmt.Fprintf(w, "Welcome to the home page!")
    89  	})
    90  }
    91  
    92  // HTTP トレーラーは、ヘッダーの前ではなく、HTTP レスポンスの後にあるヘッダーのようなキー/値のセットです。
    93  func ExampleResponseWriter_trailers() {
    94  	mux := http.NewServeMux()
    95  	mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
    96  		// WriteHeader または Write の呼び出しの前に、HTTP レスポンス中に設定するトレーラーを宣言してください。
    97  		// これらの 3 つのヘッダーは、実際にはトレーラーで送信されます。
    98  		w.Header().Set("Trailer", "AtEnd1, AtEnd2")
    99  		w.Header().Add("Trailer", "AtEnd3")
   100  
   101  		w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
   102  		w.WriteHeader(http.StatusOK)
   103  
   104  		w.Header().Set("AtEnd1", "value 1")
   105  		io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
   106  		w.Header().Set("AtEnd2", "value 2")
   107  		w.Header().Set("AtEnd3", "value 3") // これらはトレーラーとして表示されます。
   108  	})
   109  }
   110  
   111  func ExampleServer_Shutdown() {
   112  	var srv http.Server
   113  
   114  	idleConnsClosed := make(chan struct{})
   115  	go func() {
   116  		sigint := make(chan os.Signal, 1)
   117  		signal.Notify(sigint, os.Interrupt)
   118  		<-sigint
   119  
   120  		// 割り込みシグナルを受信したため、シャットダウンします。
   121  		if err := srv.Shutdown(context.Background()); err != nil {
   122  			// リスナーのクローズ時のエラー、またはコンテキストのタイムアウト:
   123  			log.Printf("HTTP server Shutdown: %v", err)
   124  		}
   125  		close(idleConnsClosed)
   126  	}()
   127  
   128  	if err := srv.ListenAndServe(); err != http.ErrServerClosed {
   129  		// リスナーの開始またはクローズ時のエラー:
   130  		log.Fatalf("HTTP server ListenAndServe: %v", err)
   131  	}
   132  
   133  	<-idleConnsClosed
   134  }
   135  
   136  func ExampleListenAndServeTLS() {
   137  	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
   138  		io.WriteString(w, "Hello, TLS!\n")
   139  	})
   140  
   141  	// crypto/tls の generate_cert.go を使用して、cert.pem と key.pem を生成できます。
   142  	log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/")
   143  	err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
   144  	log.Fatal(err)
   145  }
   146  
   147  func ExampleListenAndServe() {
   148  	// Hello world, the web server
   149  
   150  	helloHandler := func(w http.ResponseWriter, req *http.Request) {
   151  		io.WriteString(w, "Hello, world!\n")
   152  	}
   153  
   154  	http.HandleFunc("/hello", helloHandler)
   155  	log.Fatal(http.ListenAndServe(":8080", nil))
   156  }
   157  
   158  func ExampleHandleFunc() {
   159  	h1 := func(w http.ResponseWriter, _ *http.Request) {
   160  		io.WriteString(w, "Hello from a HandleFunc #1!\n")
   161  	}
   162  	h2 := func(w http.ResponseWriter, _ *http.Request) {
   163  		io.WriteString(w, "Hello from a HandleFunc #2!\n")
   164  	}
   165  
   166  	http.HandleFunc("/", h1)
   167  	http.HandleFunc("/endpoint", h2)
   168  
   169  	log.Fatal(http.ListenAndServe(":8080", nil))
   170  }
   171  
   172  func ExampleNotFoundHandler() {
   173  	mux := http.NewServeMux()
   174  
   175  	// Create sample handler to returns 404
   176  	mux.Handle("/resources", http.NotFoundHandler())
   177  
   178  	// Create sample handler that returns 200
   179  	mux.Handle("/resources/people/", newPeopleHandler())
   180  
   181  	log.Fatal(http.ListenAndServe(":8080", mux))
   182  }