User Tools

Site Tools


go:stdlib:http_server_struct

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

go:stdlib:http_server_struct [2025/12/29 23:33] – created phong2018go:stdlib:http_server_struct [2025/12/29 23:35] (current) phong2018
Line 2: Line 2:
  
 ==== What is it? ==== ==== What is it? ====
-`http.Server` is configurable HTTP server type in Go’s `net/http` package. +`http.Server` is the configurable HTTP server type in Go’s `net/http` package. 
-Compared to `http.ListenAndServe()`, it gives you more control: timeouts, graceful shutdown, TLS, limits, and logging.+It gives you more control than `http.ListenAndServe()` (timeouts, TLS, graceful shutdown, etc.).
  
 ==== What is it used for? ==== ==== What is it used for? ====
-  * Run an HTTP server with production-friendly settings (timeouts).+  * Run an HTTP server with production-ready settings (timeouts).
   * Support graceful shutdown.   * Support graceful shutdown.
   * Serve HTTPS (TLS).   * Serve HTTPS (TLS).
-  * Customize server behavior (handler, error log, header limits).+  * Customize handler, error loggermax header size, etc.
  
 ==== Key fields (common) ==== ==== Key fields (common) ====
   * `Addr`: address to listen on (e.g. `":8080"`)   * `Addr`: address to listen on (e.g. `":8080"`)
-  * `Handler`: handler/router (e.g. `mux`). If `nil`, uses `http.DefaultServeMux`. +  * `Handler`: your router/handler (e.g. `mux`) 
-  * `ReadHeaderTimeout`: max time to read request headers +  * `ReadHeaderTimeout`: limit time to read request headers 
-  * `ReadTimeout`: max time to read the entire request +  * `ReadTimeout`: total time to read request (headers + body) 
-  * `WriteTimeout`: max time allowed to write response+  * `WriteTimeout`: time allowed to write response
   * `IdleTimeout`: keep-alive idle time   * `IdleTimeout`: keep-alive idle time
-  * `MaxHeaderBytes`: maximum size of request headers +  * `ErrorLog`: custom logger 
-  * `ErrorLog`: custom logger for server errors+  * `MaxHeaderBytes`: limit request header size
  
-==== Example: server with timeouts + graceful shutdown ====+==== Example: server with timeouts ====
 <code go> <code go>
 package main package main
Line 49: Line 49:
         WriteTimeout:      10 * time.Second,         WriteTimeout:      10 * time.Second,
         IdleTimeout:       60 * time.Second,         IdleTimeout:       60 * time.Second,
-        MaxHeaderBytes:    1 << 20, // 1 MiB 
     }     }
  
-    // Start server+    // Start server in background goroutine
     go func() {     go func() {
         log.Println("listening on", srv.Addr)         log.Println("listening on", srv.Addr)
-        err := srv.ListenAndServe() +        if err := srv.ListenAndServe()err != nil && err != http.ErrServerClosed {
-        if err != nil && err != http.ErrServerClosed {+
             log.Fatal(err)             log.Fatal(err)
         }         }
     }()     }()
  
-    // Wait for termination signal+    // Graceful shutdown on SIGINT/SIGTERM
     stop := make(chan os.Signal, 1)     stop := make(chan os.Signal, 1)
     signal.Notify(stop, os.Interrupt, syscall.SIGTERM)     signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
     <-stop     <-stop
  
-    // Graceful shutdown 
     ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)     ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
     defer cancel()     defer cancel()
Line 72: Line 69:
     log.Println("shutting down...")     log.Println("shutting down...")
     _ = srv.Shutdown(ctx)     _ = srv.Shutdown(ctx)
-    log.Println("server stopped") 
 } }
 </code> </code>
  
 ==== Notes / pitfalls ==== ==== Notes / pitfalls ====
-  * `ListenAndServe()` blocks, so run it in a goroutine if you need shutdown logic+  * `ListenAndServe()` blocks; use a goroutine if you also need to handle shutdown signals
-  * Always set timeouts in production to reduce slow-client attacks. +  * Always set timeouts in production to reduce slowloris-style attacks. 
-  * `Shutdown(ctx)` waits for in-flight requests to finish (until the deadline). +  * Use `Shutdown(ctx)` for graceful shutdown; use `Close()` for immediate close.
-  * `Close()` stops immediately (may drop connections). +
-  * If you use `nil` Handler, you’re using the global `http.DefaultServeMux`.+
  
-==== Related pages ==== +==== Related ==== 
-  * [[go:stdlib:http_server|HTTP server overview]] +  * [[go:stdlib:http_server|HTTP server]] 
-  * [[go:stdlib:http_listenandserve|http.ListenAndServe]] +  * [[go:stdlib:http_server_listenandserve|http.ListenAndServe]]
-  * [[go:stdlib:middleware|Middleware]]+
   * [[go:concurrency:context|context.Context]]   * [[go:concurrency:context|context.Context]]
  
Line 94: Line 87:
   * **graceful shutdown** /ˈɡreɪsfəl ˈʃʌtdaʊn/: tắt êm (xử lý xong rồi tắt)   * **graceful shutdown** /ˈɡreɪsfəl ˈʃʌtdaʊn/: tắt êm (xử lý xong rồi tắt)
   * **TLS** /ˌtiː el ˈes/: bảo mật truyền tải (HTTPS)   * **TLS** /ˌtiː el ˈes/: bảo mật truyền tải (HTTPS)
-  * **limit** /ˈlɪmɪt/: giới hạn +  * **keep-alive** /ˌkiːp əˈlaɪv/: giữ kết nối 
-  * **in-flight request** /ɪn flaɪt rɪˈkwest/: request đang xử lý dở +  * **slowloris** /ˈsloʊˌlɔːrɪs/: kiểu tấn công giữ kết nối chậm 
-  * **deadline** /ˈdedlaɪn/: hạn chót +  * **signal** /ˈɡnəl/: tín hiệu hệ điều hành
-  * **drop** /drɑːp/: cắt (ngắt) kết nối +
-  * **attack** /əˈtæk/: tấn công +
-  * **goroutine** /ˈɡoʊruːˌtiːn/: luồng nhẹ của Go+
  
go/stdlib/http_server_struct.txt · Last modified: by phong2018