net/http

最後更新


net/http 同時提供 HTTP 伺服器與用戶端:寫 API、架網站、呼叫別人的服務,都從這個套件開始。

這個套件做什麼


HTTP 是「一問一答」的協定:用戶端送出請求(request),伺服器回一個回應(response)。net/http 把兩邊都包好了:
角色核心型別你要做的事
伺服器Handler、ServeMux、Server寫處理函式、設定路由、啟動與關閉伺服器
用戶端Client、Request、Response建立請求、送出、讀取回應

標準庫的伺服器已經可以直接上線使用,支援 HTTP/1.1、HTTP/2(HTTPS 時)、keep-alive 與並行處理:每個請求都在自己的 goroutine 中執行。Go 1.22 起 ServeMux 支援依 HTTP 方法與路徑萬用字元路由,多數專案不再需要第三方路由套件(想要更多功能可參考 Gin)。
相關套件:測試用 net/http/httptest、反向代理用 net/http/httputil、底層連線見 net、網址見 net/url。

匯入


  1. import "net/http"

本頁範例的伺服器都跑在 127.0.0.1 的隨機 port(用 httptest.NewServer 或 net.Listen("tcp", "127.0.0.1:0")),不連外網。

常用 API


http.Handler 與 HandlerFunc:處理請求的介面


伺服器處理請求的最小單位是 Handler 介面:只有一個方法 ServeHTTP(w, r)。r 是收到的請求,w(ResponseWriter)是用來寫回應的筆。
任何型別只要實作 ServeHTTP 就是 Handler。但多數時候你只想寫一個函式,這時用 http.HandlerFunc 把普通函式轉成 Handler,它是一個函式型別,自己就實作了 ServeHTTP。
簽名:
  1. type Handler interface {
  2. ServeHTTP(ResponseWriter, *Request)
  3. }
  4. type HandlerFunc func(ResponseWriter, *Request)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. )
  8. type greeter struct {
  9. name string
  10. }
  11. func (g greeter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  12. fmt.Fprintf(w, "hi from %s", g.name)
  13. }
  14. func main() {
  15. var h1 http.Handler = greeter{name: "struct"}
  16. h2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  17. fmt.Fprint(w, "hi from func")
  18. })
  19. for _, h := range []http.Handler{h1, h2} {
  20. srv := httptest.NewServer(h)
  21. resp, err := http.Get(srv.URL)
  22. if err != nil {
  23. fmt.Println(err)
  24. srv.Close()
  25. continue
  26. }
  27. body, _ := io.ReadAll(resp.Body)
  28. resp.Body.Close()
  29. fmt.Println(resp.StatusCode, string(body))
  30. srv.Close()
  31. }
  32. }

輸出:
  1. 200 hi from struct
  2. 200 hi from func

ServeMux 路由樣式:方法、萬用字元與 {$}


ServeMux 是「路由器(router)」:依請求的方法與路徑,決定交給哪個 Handler。用 http.NewServeMux() 建立,再用 HandleFunc(pattern, fn) 或 Handle(pattern, handler) 註冊。
Go 1.22 起,樣式(pattern)的格式是 [方法 ][主機]/[路徑]:
樣式符合
/static/結尾 / 代表整棵子樹:/static/ 開頭的所有路徑、任何方法
GET /posts/{id}GET(與 HEAD)且路徑為 /posts/ 加一段,例如 /posts/7
POST /posts只有 POST /posts
/files/{path...}{name...} 吃掉剩下的整段路徑,含 /
GET /{$}{$} 代表路徑到此結束,只符合 / 本身
api.example.com/只符合該主機的請求

規則重點:
  • 寫了 GET 也會符合 HEAD;其他方法必須完全相同
  • 路徑符合但方法不對,回 405 Method Not Allowed,並在 Allow 標頭列出可用的方法;路徑都不符合則回 404
  • 多個樣式都符合時,最具體的勝出(/images/thumbnails/ 比 /images/ 具體),跟註冊順序無關

簽名:
  1. func NewServeMux() *ServeMux
  2. func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
  3. func (mux *ServeMux) Handle(pattern string, handler Handler)

注意:樣式語法錯誤,或兩個樣式衝突(例如 GET / 與 /index.html 互相無法分出誰較具體),註冊時會 panic。單獨寫 / 會符合所有路徑,首頁要寫 /{$}。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "strings"
  8. )
  9. func main() {
  10. mux := http.NewServeMux()
  11. mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
  12. fmt.Fprint(w, "home")
  13. })
  14. mux.HandleFunc("GET /posts/{id}", func(w http.ResponseWriter, r *http.Request) {
  15. fmt.Fprint(w, "show post")
  16. })
  17. mux.HandleFunc("POST /posts", func(w http.ResponseWriter, r *http.Request) {
  18. fmt.Fprint(w, "create post")
  19. })
  20. mux.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
  21. fmt.Fprint(w, "static subtree")
  22. })
  23. srv := httptest.NewServer(mux)
  24. defer srv.Close()
  25. tests := []struct{ method, path string }{
  26. {"GET", "/"},
  27. {"GET", "/about"},
  28. {"GET", "/posts/7"},
  29. {"HEAD", "/posts/7"},
  30. {"POST", "/posts"},
  31. {"DELETE", "/posts"},
  32. {"GET", "/static/css/site.css"},
  33. }
  34. for _, tc := range tests {
  35. req, _ := http.NewRequest(tc.method, srv.URL+tc.path, nil)
  36. resp, err := http.DefaultClient.Do(req)
  37. if err != nil {
  38. fmt.Println(err)
  39. continue
  40. }
  41. body, _ := io.ReadAll(resp.Body)
  42. resp.Body.Close()
  43. fmt.Printf("%-6s %-22s %d %s allow=%q\n", tc.method, tc.path, resp.StatusCode,
  44. strings.TrimSpace(string(body)), resp.Header.Get("Allow"))
  45. }
  46. }

輸出:
  1. GET / 200 home allow=""
  2. GET /about 404 404 page not found allow=""
  3. GET /posts/7 200 show post allow=""
  4. HEAD /posts/7 200 allow=""
  5. POST /posts 200 create post allow=""
  6. DELETE /posts 405 Method Not Allowed allow="POST"
  7. GET /static/css/site.css 200 static subtree allow=""

Request.PathValue:取出路徑參數


樣式中 {name} 對應到的那段路徑,用 r.PathValue("name") 取出(Go 1.22 起)。名稱不存在時回傳空字串。r.Pattern(Go 1.23 起)記錄這次是哪個樣式符合,適合寫進 log 或監控指標。
簽名:
  1. func (r *Request) PathValue(name string) string

注意:PathValue 回傳的是使用者可控制的字串,拿去查資料庫或組檔案路徑前仍要驗證;數字 ID 用 strconv.Atoi 轉換並檢查錯誤。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. )
  8. func main() {
  9. mux := http.NewServeMux()
  10. mux.HandleFunc("GET /users/{uid}/orders/{oid}", func(w http.ResponseWriter, r *http.Request) {
  11. fmt.Fprintf(w, "pattern=%q uid=%s oid=%s", r.Pattern, r.PathValue("uid"), r.PathValue("oid"))
  12. })
  13. mux.HandleFunc("GET /files/{path...}", func(w http.ResponseWriter, r *http.Request) {
  14. fmt.Fprintf(w, "path=%q missing=%q", r.PathValue("path"), r.PathValue("nope"))
  15. })
  16. srv := httptest.NewServer(mux)
  17. defer srv.Close()
  18. for _, p := range []string{"/users/42/orders/A-9", "/files/img/2024/cat.png"} {
  19. resp, err := http.Get(srv.URL + p)
  20. if err != nil {
  21. fmt.Println(err)
  22. continue
  23. }
  24. body, _ := io.ReadAll(resp.Body)
  25. resp.Body.Close()
  26. fmt.Println(string(body))
  27. }
  28. }

輸出:
  1. pattern="GET /users/{uid}/orders/{oid}" uid=42 oid=A-9
  2. path="img/2024/cat.png" missing=""

ResponseWriter:標頭、狀態碼、內文的順序


寫回應有固定順序:
  1. w.Header().Set(...) 設定標頭
  2. w.WriteHeader(code) 送出狀態碼(不呼叫則預設 200)
  3. w.Write(...) 寫內文

一旦呼叫 WriteHeader 或第一次 Write,標頭就送出去了,之後再改 Header() 不會有效果。沒設 Content-Type 時,伺服器會依內文前 512 位元組自動猜測。
簽名:
  1. type ResponseWriter interface {
  2. Header() Header
  3. Write([]byte) (int, error)
  4. WriteHeader(statusCode int)
  5. }

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. )
  8. func main() {
  9. h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  10. w.Header().Set("Content-Type", "application/json")
  11. w.Header().Set("X-Request-Id", "abc123")
  12. w.WriteHeader(http.StatusCreated)
  13. w.Write([]byte(`{"ok":true}`))
  14. w.Header().Set("X-Too-Late", "ignored")
  15. })
  16. srv := httptest.NewServer(h)
  17. defer srv.Close()
  18. resp, err := http.Get(srv.URL)
  19. if err != nil {
  20. fmt.Println(err)
  21. return
  22. }
  23. defer resp.Body.Close()
  24. body, _ := io.ReadAll(resp.Body)
  25. fmt.Println(resp.Status)
  26. fmt.Println(resp.Header.Get("Content-Type"))
  27. fmt.Println(resp.Header.Get("X-Request-Id"))
  28. fmt.Printf("late=%q\n", resp.Header.Get("X-Too-Late"))
  29. fmt.Println(string(body))
  30. }

輸出:
  1. 201 Created
  2. application/json
  3. abc123
  4. late=""
  5. {"ok":true}

讀取請求:查詢參數、標頭、JSON 內文與 http.Error


*Request 上常用的資料:
想拿什麼寫法
查詢參數 ?q=gor.URL.Query().Get("q")
標頭r.Header.Get("User-Agent")(名稱不分大小寫)
內文r.Body(io.ReadCloser),例如交給 json.NewDecoder
表單欄位r.FormValue("name")

處理失敗時用 http.Error(w, 訊息, 狀態碼) 回覆純文字錯誤,記得接著 return。JSON 的解析細節見 結構體與 JSON。
簽名:
  1. func Error(w ResponseWriter, error string, code int)

注意:伺服器端不需要自己關閉 r.Body,伺服器會處理。
範例:
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/http/httptest"
  8. "strings"
  9. )
  10. type order struct {
  11. Item string `json:"item"`
  12. Qty int `json:"qty"`
  13. }
  14. func main() {
  15. mux := http.NewServeMux()
  16. mux.HandleFunc("GET /search", func(w http.ResponseWriter, r *http.Request) {
  17. q := r.URL.Query()
  18. fmt.Fprintf(w, "q=%s page=%s ua=%s", q.Get("q"), q.Get("page"), r.Header.Get("User-Agent"))
  19. })
  20. mux.HandleFunc("POST /orders", func(w http.ResponseWriter, r *http.Request) {
  21. var o order
  22. if err := json.NewDecoder(r.Body).Decode(&o); err != nil {
  23. http.Error(w, "bad json: "+err.Error(), http.StatusBadRequest)
  24. return
  25. }
  26. fmt.Fprintf(w, "ordered %d x %s", o.Qty, o.Item)
  27. })
  28. srv := httptest.NewServer(mux)
  29. defer srv.Close()
  30. req, _ := http.NewRequest("GET", srv.URL+"/search?q=gopher&page=2", nil)
  31. req.Header.Set("User-Agent", "book-demo")
  32. show(http.DefaultClient.Do(req))
  33. show(http.Post(srv.URL+"/orders", "application/json", strings.NewReader(`{"item":"tea","qty":3}`)))
  34. show(http.Post(srv.URL+"/orders", "application/json", strings.NewReader(`{oops`)))
  35. }
  36. func show(resp *http.Response, err error) {
  37. if err != nil {
  38. fmt.Println(err)
  39. return
  40. }
  41. defer resp.Body.Close()
  42. body, _ := io.ReadAll(resp.Body)
  43. fmt.Printf("%d %s\n", resp.StatusCode, strings.TrimSpace(string(body)))
  44. }

輸出:
  1. 200 q=gopher page=2 ua=book-demo
  2. 200 ordered 3 x tea
  3. 400 bad json: invalid character 'o' looking for beginning of object key string

http.MaxBytesReader:限制請求內文大小


不限制內文大小,惡意用戶端送來 10 GB 的資料就能把記憶體吃光。MaxBytesReader 包住 r.Body,超過上限時讀取會回傳 *http.MaxBytesError(Go 1.19 起),可用 errors.As 判斷後回 413。
簽名:
  1. func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser

範例:
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/http/httptest"
  8. "strings"
  9. )
  10. func main() {
  11. h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  12. r.Body = http.MaxBytesReader(w, r.Body, 10)
  13. data, err := io.ReadAll(r.Body)
  14. if err != nil {
  15. var tooLarge *http.MaxBytesError
  16. if errors.As(err, &tooLarge) {
  17. http.Error(w, fmt.Sprintf("body over %d bytes", tooLarge.Limit), http.StatusRequestEntityTooLarge)
  18. return
  19. }
  20. http.Error(w, err.Error(), http.StatusBadRequest)
  21. return
  22. }
  23. fmt.Fprintf(w, "read %d bytes", len(data))
  24. })
  25. srv := httptest.NewServer(h)
  26. defer srv.Close()
  27. for _, body := range []string{"short", "this body is far too long"} {
  28. resp, err := http.Post(srv.URL, "text/plain", strings.NewReader(body))
  29. if err != nil {
  30. fmt.Println(err)
  31. continue
  32. }
  33. b, _ := io.ReadAll(resp.Body)
  34. resp.Body.Close()
  35. fmt.Printf("%d %s\n", resp.StatusCode, strings.TrimSpace(string(b)))
  36. }
  37. }

輸出:
  1. 200 read 5 bytes
  2. 413 body over 10 bytes

中介層(middleware):包裝 Handler


「中介層」是一個接收 Handler、回傳新 Handler 的函式,用來在真正的處理前後加上共通邏輯:記錄 log、驗證身分、加標頭、攔截 panic。因為大家都是 http.Handler,可以一層一層包起來,最外層最先執行。
簽名:
  1. func(next http.Handler) http.Handler

範例中 requireToken 驗證失敗就直接回 401 並 return,不呼叫 next,請求就不會進到路由。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. )
  8. func logging(next http.Handler) http.Handler {
  9. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  10. fmt.Println("->", r.Method, r.URL.Path)
  11. next.ServeHTTP(w, r)
  12. fmt.Println("<-", r.Method, r.URL.Path)
  13. })
  14. }
  15. func requireToken(next http.Handler) http.Handler {
  16. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  17. if r.Header.Get("Authorization") != "Bearer secret" {
  18. http.Error(w, "unauthorized", http.StatusUnauthorized)
  19. return
  20. }
  21. next.ServeHTTP(w, r)
  22. })
  23. }
  24. func main() {
  25. mux := http.NewServeMux()
  26. mux.HandleFunc("GET /me", func(w http.ResponseWriter, r *http.Request) {
  27. fmt.Fprint(w, "you are admin")
  28. })
  29. srv := httptest.NewServer(logging(requireToken(mux)))
  30. defer srv.Close()
  31. for _, token := range []string{"", "Bearer secret"} {
  32. req, _ := http.NewRequest("GET", srv.URL+"/me", nil)
  33. if token != "" {
  34. req.Header.Set("Authorization", token)
  35. }
  36. resp, err := http.DefaultClient.Do(req)
  37. if err != nil {
  38. fmt.Println(err)
  39. continue
  40. }
  41. body, _ := io.ReadAll(resp.Body)
  42. resp.Body.Close()
  43. fmt.Printf("status=%d body=%q\n", resp.StatusCode, body)
  44. }
  45. }

輸出:
  1. -> GET /me
  2. <- GET /me
  3. status=401 body="unauthorized\n"
  4. -> GET /me
  5. <- GET /me
  6. status=200 body="you are admin"

http.Server:設定逾時再啟動


http.ListenAndServe(":8080", mux) 很方便,但它用的 Server 沒有任何逾時:慢速用戶端可以一直佔住連線不放(Slowloris 攻擊)。正式環境請自己建立 http.Server 並設定:
欄位限制什麼
ReadHeaderTimeout讀完請求標頭的時間,最重要的一項
ReadTimeout讀完整個請求(含內文)的時間
WriteTimeout從讀完標頭到寫完回應的時間
IdleTimeoutkeep-alive 連線閒置多久後關閉
MaxHeaderBytes請求標頭的最大位元組數

啟動方式有 ListenAndServe()(自己開 port)或 Serve(listener)(用你已開好的 listener)。它們會一直阻塞,直到伺服器關閉,關閉時回傳 http.ErrServerClosed,這不是真正的錯誤,要特別排除。
簽名:
  1. func (s *Server) ListenAndServe() error
  2. func (s *Server) Serve(l net.Listener) error
  3. func (s *Server) Close() error

注意:WriteTimeout 會切斷長時間串流(例如 SSE),這類端點需要另外處理。
範例:
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net"
  7. "net/http"
  8. "time"
  9. )
  10. func main() {
  11. mux := http.NewServeMux()
  12. mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) {
  13. fmt.Fprint(w, "hello")
  14. })
  15. srv := &http.Server{
  16. Handler: mux,
  17. ReadHeaderTimeout: 5 * time.Second,
  18. ReadTimeout: 10 * time.Second,
  19. WriteTimeout: 10 * time.Second,
  20. IdleTimeout: 60 * time.Second,
  21. MaxHeaderBytes: 1 << 20,
  22. }
  23. ln, err := net.Listen("tcp", "127.0.0.1:0")
  24. if err != nil {
  25. fmt.Println(err)
  26. return
  27. }
  28. done := make(chan error, 1)
  29. go func() { done <- srv.Serve(ln) }()
  30. resp, err := http.Get("http://" + ln.Addr().String() + "/hello")
  31. if err != nil {
  32. fmt.Println(err)
  33. return
  34. }
  35. body, _ := io.ReadAll(resp.Body)
  36. resp.Body.Close()
  37. fmt.Println(resp.StatusCode, string(body))
  38. srv.Close()
  39. err = <-done
  40. fmt.Println("serve returned:", err, errors.Is(err, http.ErrServerClosed))
  41. }

輸出:
  1. 200 hello
  2. serve returned: http: Server closed true

Server.Shutdown:優雅關閉


Close 會立刻切斷所有連線,正在處理的請求直接失敗。Shutdown 則是「優雅關閉(graceful shutdown)」:先停止接新連線,再等進行中的請求處理完,最後關閉閒置連線。傳入的 context 決定最多等多久,逾時就回傳 context 的錯誤。實務上通常搭配 os/signal 在收到 Ctrl+C 時呼叫。RegisterOnShutdown 可以註冊關閉時要執行的函式。
簽名:
  1. func (s *Server) Shutdown(ctx context.Context) error
  2. func (s *Server) RegisterOnShutdown(f func())

注意:呼叫 Shutdown 後,Serve 會立刻回傳 ErrServerClosed。如果 main 在那時就結束,進行中的請求一樣會被中斷,所以要等 Shutdown 回傳後才讓程式退出。
範例:
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/http"
  9. "time"
  10. )
  11. func main() {
  12. started := make(chan struct{})
  13. mux := http.NewServeMux()
  14. mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
  15. close(started)
  16. time.Sleep(300 * time.Millisecond)
  17. fmt.Fprint(w, "slow job finished")
  18. })
  19. srv := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}
  20. srv.RegisterOnShutdown(func() { fmt.Println("shutdown hook") })
  21. ln, _ := net.Listen("tcp", "127.0.0.1:0")
  22. serveErr := make(chan error, 1)
  23. go func() { serveErr <- srv.Serve(ln) }()
  24. result := make(chan string, 1)
  25. go func() {
  26. resp, err := http.Get("http://" + ln.Addr().String() + "/slow")
  27. if err != nil {
  28. result <- err.Error()
  29. return
  30. }
  31. defer resp.Body.Close()
  32. b, _ := io.ReadAll(resp.Body)
  33. result <- string(b)
  34. }()
  35. <-started
  36. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  37. defer cancel()
  38. fmt.Println("shutdown:", srv.Shutdown(ctx))
  39. fmt.Println("client got:", <-result)
  40. fmt.Println("serve:", errors.Is(<-serveErr, http.ErrServerClosed))
  41. }

輸出:
  1. shutdown hook
  2. shutdown: <nil>
  3. client got: slow job finished
  4. serve: true

http.Client:送出請求並設定逾時


http.Get、http.Post 用的是 http.DefaultClient,它沒有逾時,對方不回應就永遠卡住。自己建立 &http.Client{Timeout: ...},這個時間涵蓋連線、送出、讀完回應內文的全程。
Client 內部有連線池,可以安全地被多個 goroutine 共用,整個程式建立一個重複使用即可,不要每次請求都建新的。
簽名:
  1. type Client struct {
  2. Transport RoundTripper
  3. CheckRedirect func(req *Request, via []*Request) error
  4. Jar CookieJar
  5. Timeout time.Duration
  6. }
  7. func (c *Client) Get(url string) (resp *Response, err error)
  8. func (c *Client) Do(req *Request) (*Response, error)

注意:err == nil 時一定要 resp.Body.Close(),否則連線無法回到連線池而洩漏。非 2xx 狀態碼(404、500)不是 err,要自己檢查 resp.StatusCode。
範例:
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/http/httptest"
  8. "time"
  9. )
  10. func main() {
  11. mux := http.NewServeMux()
  12. mux.HandleFunc("GET /fast", func(w http.ResponseWriter, r *http.Request) {
  13. fmt.Fprint(w, "quick")
  14. })
  15. mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
  16. select {
  17. case <-time.After(2 * time.Second):
  18. case <-r.Context().Done():
  19. }
  20. })
  21. srv := httptest.NewServer(mux)
  22. defer srv.Close()
  23. client := &http.Client{Timeout: 200 * time.Millisecond}
  24. resp, err := client.Get(srv.URL + "/fast")
  25. if err != nil {
  26. fmt.Println(err)
  27. return
  28. }
  29. body, _ := io.ReadAll(resp.Body)
  30. resp.Body.Close()
  31. fmt.Println(resp.StatusCode, string(body))
  32. _, err = client.Get(srv.URL + "/slow")
  33. var te interface{ Timeout() bool }
  34. fmt.Println("timeout:", errors.As(err, &te) && te.Timeout())
  35. }

輸出:
  1. 200 quick
  2. timeout: true

http.NewRequestWithContext:自訂請求


要用 PUT/DELETE、加標頭、或讓單一請求可以被取消,就自己建立 *Request 再交給 Client.Do。NewRequestWithContext 讓請求綁定一個 context:context 逾時或被取消,請求會立刻中止,Do 回傳的錯誤可用 errors.Is(err, context.DeadlineExceeded) 判斷。
這比 Client.Timeout 更靈活:每個請求可以有不同期限,也能跟著上游的請求一起取消。方法名稱建議用 http.MethodPut 這類常數,避免打錯字。
簽名:
  1. func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)

範例:
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/http/httptest"
  9. "strings"
  10. "time"
  11. )
  12. func main() {
  13. mux := http.NewServeMux()
  14. mux.HandleFunc("PUT /notes/{id}", func(w http.ResponseWriter, r *http.Request) {
  15. b, _ := io.ReadAll(r.Body)
  16. fmt.Fprintf(w, "note %s = %s (%s)", r.PathValue("id"), b, r.Header.Get("Content-Type"))
  17. })
  18. mux.HandleFunc("GET /wait", func(w http.ResponseWriter, r *http.Request) {
  19. select {
  20. case <-time.After(2 * time.Second):
  21. case <-r.Context().Done():
  22. }
  23. })
  24. srv := httptest.NewServer(mux)
  25. defer srv.Close()
  26. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  27. defer cancel()
  28. req, err := http.NewRequestWithContext(ctx, http.MethodPut, srv.URL+"/notes/9", strings.NewReader("buy milk"))
  29. if err != nil {
  30. fmt.Println(err)
  31. return
  32. }
  33. req.Header.Set("Content-Type", "text/plain")
  34. resp, err := http.DefaultClient.Do(req)
  35. if err != nil {
  36. fmt.Println(err)
  37. return
  38. }
  39. body, _ := io.ReadAll(resp.Body)
  40. resp.Body.Close()
  41. fmt.Println(resp.StatusCode, string(body))
  42. short, cancel2 := context.WithTimeout(context.Background(), 100*time.Millisecond)
  43. defer cancel2()
  44. req2, _ := http.NewRequestWithContext(short, http.MethodGet, srv.URL+"/wait", nil)
  45. _, err = http.DefaultClient.Do(req2)
  46. fmt.Println("deadline:", errors.Is(err, context.DeadlineExceeded))
  47. }

輸出:
  1. 200 note 9 = buy milk (text/plain)
  2. deadline: true

http.FileServerFS 與 StripPrefix:提供靜態檔案


FileServerFS(Go 1.22 起)把一個 fs.FS 變成提供檔案下載的 Handler,會自動設定 Content-Type、處理 404 與快取標頭。搭配 embed 可以把網站檔案編進執行檔。
路由掛在 /assets/ 底下時,請求路徑是 /assets/css/app.css,但檔案系統裡是 css/app.css,用 StripPrefix 先去掉前綴再交給 FileServer。範例用 testing/fstest.MapFS 在記憶體中模擬檔案系統。
簽名:
  1. func FileServerFS(root fs.FS) Handler
  2. func StripPrefix(prefix string, h Handler) Handler

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "testing/fstest"
  8. )
  9. func main() {
  10. files := fstest.MapFS{
  11. "index.html": {Data: []byte("<h1>home</h1>")},
  12. "css/app.css": {Data: []byte("body{margin:0}")},
  13. }
  14. mux := http.NewServeMux()
  15. mux.Handle("GET /assets/", http.StripPrefix("/assets/", http.FileServerFS(files)))
  16. srv := httptest.NewServer(mux)
  17. defer srv.Close()
  18. for _, p := range []string{"/assets/css/app.css", "/assets/missing.txt"} {
  19. resp, err := http.Get(srv.URL + p)
  20. if err != nil {
  21. fmt.Println(err)
  22. continue
  23. }
  24. body, _ := io.ReadAll(resp.Body)
  25. resp.Body.Close()
  26. fmt.Printf("%d %-24s %q\n", resp.StatusCode, resp.Header.Get("Content-Type"), body)
  27. }
  28. }

輸出:
  1. 200 text/css; charset=utf-8 "body{margin:0}"
  2. 404 text/plain; charset=utf-8 "404 page not found\n"

重點整理


  • 伺服器的核心是 Handler 介面;一般函式用 HandlerFunc 轉換
  • Go 1.22 起 ServeMux 支援 "GET /posts/{id}" 樣式,用 r.PathValue("id") 取值;首頁寫 /{$}
  • 寫回應的順序:Header().Set → WriteHeader → Write
  • 正式環境自己建 http.Server 並至少設 ReadHeaderTimeout;關閉用 Shutdown,並排除 ErrServerClosed
  • 用戶端自建 http.Client{Timeout: ...} 並重複使用;每個請求用 NewRequestWithContext 綁 context
  • 拿到 resp 就要 defer resp.Body.Close(),並自己檢查 StatusCode

資料來源