go:stdlib:http_server
Differences
This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| go:stdlib:http_server [2025/12/29 23:27] – created phong2018 | go:stdlib:http_server [2025/12/29 23:33] (current) – phong2018 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | ===== http.Server ===== | + | ===== HTTP Server |
| ==== What is it? ==== | ==== What is it? ==== | ||
| - | `http.Server` is the configurable | + | An **HTTP server** is a program |
| - | It gives you more control than `http.ListenAndServe()` (timeouts, TLS, graceful shutdown, etc.). | + | * **listens** on an address |
| + | * accepts incoming HTTP connections/ | ||
| + | * 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 |
| - | * Customize handler, error logger, max header size, etc. | + | |
| - | ==== Key fields (common) | + | ==== Core building blocks |
| - | * `Addr`: address to listen on (e.g. `": | + | * **Handler**: processes requests and writes responses |
| - | * `Handler`: your router/ | + | |
| - | * `ReadHeaderTimeout`: limit time to read request | + | * `http.HandlerFunc` (function adapter) |
| - | * `ReadTimeout`: total time to read request (headers | + | * **ResponseWriter**: writes status code, headers, and body. |
| - | * `WriteTimeout`: time allowed | + | * **Request**: method, URL, headers, body, context. |
| - | * `IdleTimeout`: | + | * **ServeMux (router)**: maps URL paths to handlers |
| - | * `ErrorLog`: custom logger | + | * `http.DefaultServeMux` is the default global mux. |
| - | * `MaxHeaderBytes`: limit request header size | + | * `http.NewServeMux()` creates a dedicated mux. |
| - | ==== Example: | + | ==== Minimal |
| <code go> | <code go> | ||
| package main | package main | ||
| import ( | import ( | ||
| - | " | ||
| " | " | ||
| " | " | ||
| - | " | ||
| - | " | ||
| - | " | ||
| - | " | ||
| ) | ) | ||
| func main() { | func main() { | ||
| mux := http.NewServeMux() | mux := http.NewServeMux() | ||
| + | |||
| + | mux.HandleFunc("/", | ||
| + | w.Write([]byte(" | ||
| + | }) | ||
| + | |||
| mux.HandleFunc("/ | mux.HandleFunc("/ | ||
| w.WriteHeader(http.StatusOK) | w.WriteHeader(http.StatusOK) | ||
| Line 42: | Line 46: | ||
| }) | }) | ||
| - | | + | log.Println(" |
| - | Addr: ": | + | log.Fatal(http.ListenAndServe(":8080", mux)) |
| - | Handler: | + | |
| - | ReadHeaderTimeout: | + | |
| - | ReadTimeout: | + | |
| - | WriteTimeout: | + | |
| - | IdleTimeout: | + | |
| - | } | + | |
| - | + | ||
| - | // Start server in background goroutine | + | |
| - | go func() { | + | |
| - | | + | |
| - | if err := srv.ListenAndServe(); | + | |
| - | | + | |
| - | } | + | |
| - | }() | + | |
| - | + | ||
| - | // Graceful shutdown on SIGINT/ | + | |
| - | stop := make(chan os.Signal, 1) | + | |
| - | signal.Notify(stop, os.Interrupt, | + | |
| - | <-stop | + | |
| - | + | ||
| - | ctx, cancel | + | |
| - | defer cancel() | + | |
| - | + | ||
| - | log.Println(" | + | |
| - | _ = srv.Shutdown(ctx) | + | |
| } | } | ||
| </ | </ | ||
| - | ==== Notes / pitfalls | + | ==== Common patterns |
| - | * `ListenAndServe()` | + | * **Default mux pattern** (quick demos): use `http.HandleFunc` + `ListenAndServe(..., nil)` |
| - | * Always set timeouts in production to reduce slowloris-style attacks. | + | * **Custom mux pattern** (recommended): |
| - | * Use `Shutdown(ctx)` for graceful shutdown; use `Close()` for immediate close. | + | * **Middleware pattern**: wrap handlers |
| + | |||
| + | ==== Production notes (important) ==== | ||
| + | For production, prefer | ||
| + | Time-outs help protect against slow-client attacks and avoid hanging connections. | ||
| - | ==== Related ==== | + | ==== Related |
| - | * [[go: | + | * [[go: |
| - | * [[go: | + | * [[go: |
| - | * [[go:concurrency:context|context.Context]] | + | * [[go:stdlib:http_client|http.Client]] |
| + | * [[go: | ||
| + | * [[go: | ||
| ==== Hard words (English) ==== | ==== Hard words (English) ==== | ||
| - | * **configurable** /kənˈfɪɡjərəbəl/: cấu hình được | + | * **server** /ˈsɝːvər/: |
| + | * **service** / | ||
| + | * **listen** / | ||
| + | * **accept** /əkˈsept/: chấp nhận kết nối/ | ||
| + | * **handler** / | ||
| + | * **interface** /ˈɪntərfeɪs/: | ||
| + | * **adapter** /əˈdæptər/: bộ chuyển/ | ||
| + | * **router** /ˈruːtər/: bộ định tuyến (map path -> handler) | ||
| + | * **multiplexer (mux)** / | ||
| + | * **webhook** / | ||
| + | * **load balancer** /ˈloʊd ˌbælənser/: | ||
| + | * **middleware** / | ||
| + | * **graceful shutdown** / | ||
| * **timeout** / | * **timeout** / | ||
| - | * **graceful shutdown** /ˈɡreɪsfəl ˈʃʌtdaʊn/: tắt êm (xử lý xong rồi tắt) | + | * **hanging** /ˈhæŋɪŋ/: treo/chờ mãi |
| - | * **TLS** | + | |
| - | * **keep-alive** /ˌkiːp əˈlaɪv/: giữ kết nối | + | |
| - | * **slowloris** / | + | |
| - | * **signal** / | + | |
go/stdlib/http_server.1767050862.txt.gz · Last modified: by phong2018
