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

Both sides previous revisionPrevious revision
go:stdlib:http_server [2025/12/29 23:29] 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? ====
 An **HTTP server** is a program (service) that: An **HTTP server** is a program (service) that:
-  * **listens** on a network address (host:port), and +  * **listens** on an address (host:port), 
-  * **handles** incoming HTTP requeststhen +  * accepts incoming HTTP connections/requests, 
-  * sends back HTTP responses.+  runs a **handler** to process each request
 +  * writes an HTTP response (status + headers + body).
  
-In Go, you commonly build HTTP servers using the standard library package `net/http`.+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? ====
-  * Build web APIs (REST) and microservices. +  * Build REST APIs and microservices. 
-  * Serve web pages, JSON, files. +  * Serve web pages, JSON, files, webhooks
-  * Provide health checks (e.g. `/health`) for monitoring and load balancers.+  * Provide health checks (e.g. `/health`) for monitoring/load balancers.
  
-==== How it works (simple flow) ==== +==== Core building blocks ==== 
-  - Client (browser/appsends an HTTP request (example: `GET /health`) +  * **Handler**: processes requests and writes responses   
-  - Server receives the request +    * `http.Handler` (interface) 
-  - Server calls a **handler** +    * `http.HandlerFunc(function adapter
-  - Handler writes an HTTP response (status code headers body)+  * **ResponseWriter**: writes status codeheaders, and body
 +  * **Request**: method, URL, headers, body, context. 
 +  * **ServeMux (router)**: maps URL paths to handlers   
 +    * `http.DefaultServeMux` is the default global mux. 
 +    * `http.NewServeMux()` creates a dedicated mux.
  
-==== Minimal example (Go net/http) ====+==== Minimal server (custom mux) ====
 <code go> <code go>
 package main package main
  
-import "net/http"+import 
 +    "log" 
 +    "net/http" 
 +)
  
 func main() { func main() {
-    http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {+    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) {
         w.WriteHeader(http.StatusOK)         w.WriteHeader(http.StatusOK)
         w.Write([]byte("ok"))         w.Write([]byte("ok"))
     })     })
  
-    http.ListenAndServe(":8080", nil)+    log.Println("listening on :8080"
 +    log.Fatal(http.ListenAndServe(":8080", mux))
 } }
 </code> </code>
  
-==== Key concepts ==== +==== Common patterns ==== 
-  * **Handler**: code that processes a request and writes a response+  * **Default mux pattern** (quick demos)use `http.HandleFunc` + `ListenAndServe(..., nil)` 
-  * **ResponseWriter**: used to write headers/status/body+  * **Custom mux pattern** (recommended)`mux := http.NewServeMux()` and pass it to server 
-  * **Request**: contains methodURLheadersbody, context. +  * **Middleware pattern**: wrap handlers (loggingauthrecoverrate limit) 
-  * **ServeMux (router)**: maps URL paths to handlers.+ 
 +==== 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 pages ==== ==== Related pages ====
-  * [[go:stdlib:http_server_listenandserve|http.ListenAndServe]] +  * [[go:stdlib:http_server_struct|http.Server]] 
-  * [[go:stdlib:http_server|http.Server]]+  * [[go:stdlib:http_listenandserve|http.ListenAndServe]]
   * [[go:stdlib:http_client|http.Client]]   * [[go:stdlib:http_client|http.Client]]
   * [[go:stdlib:middleware|Middleware]]   * [[go:stdlib:middleware|Middleware]]
 +  * [[go:stdlib:httptest|httptest]]
  
 ==== Hard words (English) ==== ==== Hard words (English) ====
Line 52: Line 71:
   * **service** /ˈsɝːvɪs/: dịch vụ   * **service** /ˈsɝːvɪs/: dịch vụ
   * **listen** /ˈlɪsən/: lắng nghe (mở cổng nhận kết nối)   * **listen** /ˈlɪsən/: lắng nghe (mở cổng nhận kết nối)
-  * **handle** /ˈhændəl/: xử lý +  * **accept** /əkˈsept/: chấp nhận kết nối/nhận vào 
-  * **request** /ˈkwest/: yêu cầu +  * **handler** /ˈhændlər/: bộ xử lý request 
-  * **response** /rɪˈspɑːns/: phản hồi +  * **interface** /ˈɪntərfeɪs/: giao diện (hợp đồng
-  * **status code** /ˈsteɪtəs koʊd/: mã trạng thái (200, 404, 500...+  * **adapter** /əˈdæptər/: bộ chuyển/đệm để khớp kiểu
-  * **header** /ˈhedər/: header (thông tin kèm theo) +
-  * **body** /ˈbɑːdi/: nội dung+
   * **router** /ˈruːtər/: bộ định tuyến (map path -> handler)   * **router** /ˈruːtər/: bộ định tuyến (map path -> handler)
-  * **health check** /helθ ek/: kiểm tra tình trạng+  * **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ọc handler) 
 +  * **graceful shutdown** /ˈɡreɪsfəl ˈʃʌtdaʊn/: tắt êm 
 +  * **timeout** /ˈtaɪmaʊt/: hết thời gian chờ 
 +  * **hanging** /ˈhæŋɪŋ/: treo/chờ mãi
  
go/stdlib/http_server.txt · Last modified: by phong2018