User Tools

Site Tools


go:stdlib:http_server

Differences

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

Link to this comparison view

Next revision
Previous revision
go:stdlib:http_server [2025/12/29 23:27] – created phong2018go:stdlib:http_server [2025/12/29 23:33] (current) phong2018
Line 1: Line 1:
-===== http.Server =====+===== HTTP Server (net/http) =====
  
 ==== What is it? ==== ==== What is it? ====
-`http.Server` is the configurable HTTP server type in Go’s `net/http` package. +An **HTTP server** is a program (servicethat: 
-It gives you more control than `http.ListenAndServe()(timeoutsTLSgraceful shutdownetc.).+  * **listens** on an address (host:port), 
 +  * accepts incoming HTTP connections/requests, 
 +  * runs a **handler** to process each request, 
 +  * writes an HTTP response (status + headers + body)
 + 
 +In Go, the standard library package `net/http` provides everything needed to build an HTTP server.
  
 ==== What is it used for? ==== ==== What is it used for? ====
-  * Run an HTTP server with production-ready settings (timeouts)+  * Build REST APIs and microservices
-  * Support graceful shutdown+  * Serve web pages, JSON, files, webhooks
-  * Serve HTTPS (TLS)+  * Provide health checks (e.g. `/health`for monitoring/load balancers.
-  * Customize handler, error logger, max header size, etc.+
  
-==== Key fields (common) ==== +==== Core building blocks ==== 
-  * `Addr`address to listen on (e.g. `":8080"`) +  * **Handler**processes requests and writes responses   
-  * `Handler`: your router/handler (e.g. `mux`+    * `http.Handler` (interface) 
-  * `ReadHeaderTimeout`limit time to read request headers +    * `http.HandlerFunc(function adapter
-  * `ReadTimeout`total time to read request (headers body) +  * **ResponseWriter**writes status code, headers, and body. 
-  * `WriteTimeout`time allowed to write response +  * **Request**method, URL, headersbody, context. 
-  * `IdleTimeout`: keep-alive idle time +  * **ServeMux (router)**maps URL paths to handlers   
-  * `ErrorLog`: custom logger +    * `http.DefaultServeMuxis the default global mux. 
-  * `MaxHeaderBytes`: limit request header size+    * `http.NewServeMux()creates a dedicated mux.
  
-==== Example: server with timeouts ====+==== Minimal server (custom mux) ====
 <code go> <code go>
 package main package main
  
 import ( import (
-    "context" 
     "log"     "log"
     "net/http"     "net/http"
-    "os" 
-    "os/signal" 
-    "syscall" 
-    "time" 
 ) )
  
 func main() { func main() {
     mux := http.NewServeMux()     mux := http.NewServeMux()
 +
 +    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
 +        w.Write([]byte("hello"))
 +    })
 +
     mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {     mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
         w.WriteHeader(http.StatusOK)         w.WriteHeader(http.StatusOK)
Line 42: Line 46:
     })     })
  
-    srv := &http.Server{ +    log.Println("listening on :8080") 
-        Addr:              ":8080", +    log.Fatal(http.ListenAndServe(":8080"mux))
-        Handler:           mux, +
-        ReadHeaderTimeout: 5 * time.Second, +
-        ReadTimeout:       10 * time.Second, +
-        WriteTimeout:      10 * time.Second, +
-        IdleTimeout:       60 * time.Second, +
-    } +
- +
-    // Start server in background goroutine +
-    go func() { +
-        log.Println("listening on", srv.Addr+
-        if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { +
-            log.Fatal(err) +
-        } +
-    }() +
- +
-    // Graceful shutdown on SIGINT/SIGTERM +
-    stop := make(chan os.Signal, 1) +
-    signal.Notify(stop, os.Interrupt, syscall.SIGTERM) +
-    <-stop +
- +
-    ctx, cancel := context.WithTimeout(context.Background()5*time.Second) +
-    defer cancel() +
- +
-    log.Println("shutting down..."+
-    _ = srv.Shutdown(ctx)+
 } }
 </code> </code>
  
-==== Notes / pitfalls ==== +==== Common patterns ==== 
-  * `ListenAndServe()` blocks; use a goroutine if you also need to handle shutdown signals. +  * **Default mux pattern** (quick demos): use `http.HandleFunc` + `ListenAndServe(..., nil)` 
-  * Always set timeouts in production to reduce slowloris-style attacks+  * **Custom mux pattern** (recommended): `mux := http.NewServeMux()` and pass it to server 
-  * Use `Shutdown(ctx)` for graceful shutdown; use `Close()` for immediate close.+  * **Middleware pattern**: wrap handlers (logging, auth, recover, rate limit) 
 + 
 +==== Production notes (important==== 
 +For production, prefer `http.Server{...}` with timeouts and graceful shutdown. 
 +Time-outs help protect against slow-client attacks and avoid hanging connections.
  
-==== Related ==== +==== Related pages ==== 
-  * [[go:stdlib:http_server|HTTP server]] +  * [[go:stdlib:http_server_struct|http.Server]] 
-  * [[go:stdlib:http_server_listenandserve|http.ListenAndServe]] +  * [[go:stdlib:http_listenandserve|http.ListenAndServe]] 
-  * [[go:concurrency:context|context.Context]]+  * [[go:stdlib:http_client|http.Client]] 
 +  * [[go:stdlib:middleware|Middleware]] 
 +  * [[go:stdlib:httptest|httptest]]
  
 ==== Hard words (English) ==== ==== Hard words (English) ====
-  * **configurable** /kənˈfɪɡjərəbəl/: cấu hình đưc+  * **server** /ˈsɝːvər/: máy chủ / dịch vụ phục vụ 
 +  * **service** /ˈsɝːvɪs/: dịch vụ 
 +  * **listen** /ˈlɪsən/: lắng nghe (mở cổng nhận kết nối) 
 +  * **accept** /əkˈsept/: chấp nhậkết nối/nhận vào 
 +  * **handler** /ˈhændlər/: bộ xử lý request 
 +  * **interface** /ˈɪntərfeɪs/: giao diện (hợp đồng) 
 +  * **adapter** /əˈdæptər/: bộ chuyển/đệm để khớp kiểu 
 +  * **router** /ˈruːtər/: bộ định tuyến (map path -> handler) 
 +  * **multiplexer (mux)** /ˈmʌltɪˌpleksər/: bộ chọn route theo đường dẫn 
 +  * **webhook** /ˈwebhʊk/: callback qua HTTP 
 +  * **load balancer** /ˈloʊd ˌbælənser/: cân bằng tải 
 +  * **middleware** /ˈmɪdəlwer/: lớp trung gian (bọhandler) 
 +  * **graceful shutdown** /ˈɡreɪsfəl ˈʃʌtdaʊn/: tắt êm
   * **timeout** /ˈtaɪmaʊt/: hết thời gian chờ   * **timeout** /ˈtaɪmaʊt/: hết thời gian chờ
-  * **graceful shutdown** /ˈɡreɪsfəl ˈʃʌtdaʊn/: tắt êm (xử lý xong rồi tắt) +  * **hanging** /ˈhæŋɪŋ/: treo/chờ mãi
-  * **TLS** /ˌtiː el ˈes/: bảo mật truyền tải (HTTPS) +
-  * **keep-alive** /ˌkiːp əˈlaɪv/: giữ kết nối +
-  * **slowloris** /ˈsloʊˌlɔːrɪs/: kiểu tấn công giữ kết nối chậm +
-  * **signal** /ˈsɪɡnəl/: tín hiệu hệ điều hành+
  
go/stdlib/http_server.1767050862.txt.gz · Last modified: by phong2018