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。
匯入
- 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。簽名:
- type Handler interface {
- ServeHTTP(ResponseWriter, *Request)
- }
- type HandlerFunc func(ResponseWriter, *Request)
範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- )
- type greeter struct {
- name string
- }
- func (g greeter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintf(w, "hi from %s", g.name)
- }
- func main() {
- var h1 http.Handler = greeter{name: "struct"}
- h2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, "hi from func")
- })
- for _, h := range []http.Handler{h1, h2} {
- srv := httptest.NewServer(h)
- resp, err := http.Get(srv.URL)
- if err != nil {
- fmt.Println(err)
- srv.Close()
- continue
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Println(resp.StatusCode, string(body))
- srv.Close()
- }
- }
輸出:
- 200 hi from struct
- 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/具體),跟註冊順序無關
簽名:
- func NewServeMux() *ServeMux
- func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
- func (mux *ServeMux) Handle(pattern string, handler Handler)
注意:樣式語法錯誤,或兩個樣式衝突(例如
GET / 與 /index.html 互相無法分出誰較具體),註冊時會 panic。單獨寫 / 會符合所有路徑,首頁要寫 /{$}。範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "strings"
- )
- func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, "home")
- })
- mux.HandleFunc("GET /posts/{id}", func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, "show post")
- })
- mux.HandleFunc("POST /posts", func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, "create post")
- })
- mux.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, "static subtree")
- })
- srv := httptest.NewServer(mux)
- defer srv.Close()
- tests := []struct{ method, path string }{
- {"GET", "/"},
- {"GET", "/about"},
- {"GET", "/posts/7"},
- {"HEAD", "/posts/7"},
- {"POST", "/posts"},
- {"DELETE", "/posts"},
- {"GET", "/static/css/site.css"},
- }
- for _, tc := range tests {
- req, _ := http.NewRequest(tc.method, srv.URL+tc.path, nil)
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- fmt.Println(err)
- continue
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Printf("%-6s %-22s %d %s allow=%q\n", tc.method, tc.path, resp.StatusCode,
- strings.TrimSpace(string(body)), resp.Header.Get("Allow"))
- }
- }
輸出:
- GET / 200 home allow=""
- GET /about 404 404 page not found allow=""
- GET /posts/7 200 show post allow=""
- HEAD /posts/7 200 allow=""
- POST /posts 200 create post allow=""
- DELETE /posts 405 Method Not Allowed allow="POST"
- GET /static/css/site.css 200 static subtree allow=""
Request.PathValue:取出路徑參數
樣式中
{name} 對應到的那段路徑,用 r.PathValue("name") 取出(Go 1.22 起)。名稱不存在時回傳空字串。r.Pattern(Go 1.23 起)記錄這次是哪個樣式符合,適合寫進 log 或監控指標。簽名:
- func (r *Request) PathValue(name string) string
注意:
PathValue 回傳的是使用者可控制的字串,拿去查資料庫或組檔案路徑前仍要驗證;數字 ID 用 strconv.Atoi 轉換並檢查錯誤。範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- )
- func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("GET /users/{uid}/orders/{oid}", func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintf(w, "pattern=%q uid=%s oid=%s", r.Pattern, r.PathValue("uid"), r.PathValue("oid"))
- })
- mux.HandleFunc("GET /files/{path...}", func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintf(w, "path=%q missing=%q", r.PathValue("path"), r.PathValue("nope"))
- })
- srv := httptest.NewServer(mux)
- defer srv.Close()
- for _, p := range []string{"/users/42/orders/A-9", "/files/img/2024/cat.png"} {
- resp, err := http.Get(srv.URL + p)
- if err != nil {
- fmt.Println(err)
- continue
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Println(string(body))
- }
- }
輸出:
- pattern="GET /users/{uid}/orders/{oid}" uid=42 oid=A-9
- path="img/2024/cat.png" missing=""
ResponseWriter:標頭、狀態碼、內文的順序
寫回應有固定順序:
w.Header().Set(...)設定標頭w.WriteHeader(code)送出狀態碼(不呼叫則預設 200)w.Write(...)寫內文
一旦呼叫
WriteHeader 或第一次 Write,標頭就送出去了,之後再改 Header() 不會有效果。沒設 Content-Type 時,伺服器會依內文前 512 位元組自動猜測。簽名:
- type ResponseWriter interface {
- Header() Header
- Write([]byte) (int, error)
- WriteHeader(statusCode int)
- }
範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- )
- func main() {
- h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- w.Header().Set("X-Request-Id", "abc123")
- w.WriteHeader(http.StatusCreated)
- w.Write([]byte(`{"ok":true}`))
- w.Header().Set("X-Too-Late", "ignored")
- })
- srv := httptest.NewServer(h)
- defer srv.Close()
- resp, err := http.Get(srv.URL)
- if err != nil {
- fmt.Println(err)
- return
- }
- defer resp.Body.Close()
- body, _ := io.ReadAll(resp.Body)
- fmt.Println(resp.Status)
- fmt.Println(resp.Header.Get("Content-Type"))
- fmt.Println(resp.Header.Get("X-Request-Id"))
- fmt.Printf("late=%q\n", resp.Header.Get("X-Too-Late"))
- fmt.Println(string(body))
- }
輸出:
- 201 Created
- application/json
- abc123
- late=""
- {"ok":true}
讀取請求:查詢參數、標頭、JSON 內文與 http.Error
*Request 上常用的資料:| 想拿什麼 | 寫法 |
|---|---|
查詢參數 ?q=go | r.URL.Query().Get("q") |
| 標頭 | r.Header.Get("User-Agent")(名稱不分大小寫) |
| 內文 | r.Body(io.ReadCloser),例如交給 json.NewDecoder |
| 表單欄位 | r.FormValue("name") |
處理失敗時用
http.Error(w, 訊息, 狀態碼) 回覆純文字錯誤,記得接著 return。JSON 的解析細節見 結構體與 JSON。簽名:
- func Error(w ResponseWriter, error string, code int)
注意:伺服器端不需要自己關閉
r.Body,伺服器會處理。範例:
- package main
- import (
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "strings"
- )
- type order struct {
- Item string `json:"item"`
- Qty int `json:"qty"`
- }
- func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("GET /search", func(w http.ResponseWriter, r *http.Request) {
- q := r.URL.Query()
- fmt.Fprintf(w, "q=%s page=%s ua=%s", q.Get("q"), q.Get("page"), r.Header.Get("User-Agent"))
- })
- mux.HandleFunc("POST /orders", func(w http.ResponseWriter, r *http.Request) {
- var o order
- if err := json.NewDecoder(r.Body).Decode(&o); err != nil {
- http.Error(w, "bad json: "+err.Error(), http.StatusBadRequest)
- return
- }
- fmt.Fprintf(w, "ordered %d x %s", o.Qty, o.Item)
- })
- srv := httptest.NewServer(mux)
- defer srv.Close()
- req, _ := http.NewRequest("GET", srv.URL+"/search?q=gopher&page=2", nil)
- req.Header.Set("User-Agent", "book-demo")
- show(http.DefaultClient.Do(req))
- show(http.Post(srv.URL+"/orders", "application/json", strings.NewReader(`{"item":"tea","qty":3}`)))
- show(http.Post(srv.URL+"/orders", "application/json", strings.NewReader(`{oops`)))
- }
- func show(resp *http.Response, err error) {
- if err != nil {
- fmt.Println(err)
- return
- }
- defer resp.Body.Close()
- body, _ := io.ReadAll(resp.Body)
- fmt.Printf("%d %s\n", resp.StatusCode, strings.TrimSpace(string(body)))
- }
輸出:
- 200 q=gopher page=2 ua=book-demo
- 200 ordered 3 x tea
- 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。簽名:
- func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
範例:
- package main
- import (
- "errors"
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "strings"
- )
- func main() {
- h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, 10)
- data, err := io.ReadAll(r.Body)
- if err != nil {
- var tooLarge *http.MaxBytesError
- if errors.As(err, &tooLarge) {
- http.Error(w, fmt.Sprintf("body over %d bytes", tooLarge.Limit), http.StatusRequestEntityTooLarge)
- return
- }
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- fmt.Fprintf(w, "read %d bytes", len(data))
- })
- srv := httptest.NewServer(h)
- defer srv.Close()
- for _, body := range []string{"short", "this body is far too long"} {
- resp, err := http.Post(srv.URL, "text/plain", strings.NewReader(body))
- if err != nil {
- fmt.Println(err)
- continue
- }
- b, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Printf("%d %s\n", resp.StatusCode, strings.TrimSpace(string(b)))
- }
- }
輸出:
- 200 read 5 bytes
- 413 body over 10 bytes
中介層(middleware):包裝 Handler
「中介層」是一個接收 Handler、回傳新 Handler 的函式,用來在真正的處理前後加上共通邏輯:記錄 log、驗證身分、加標頭、攔截 panic。因為大家都是
http.Handler,可以一層一層包起來,最外層最先執行。簽名:
- func(next http.Handler) http.Handler
範例中
requireToken 驗證失敗就直接回 401 並 return,不呼叫 next,請求就不會進到路由。範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- )
- func logging(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Println("->", r.Method, r.URL.Path)
- next.ServeHTTP(w, r)
- fmt.Println("<-", r.Method, r.URL.Path)
- })
- }
- func requireToken(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Header.Get("Authorization") != "Bearer secret" {
- http.Error(w, "unauthorized", http.StatusUnauthorized)
- return
- }
- next.ServeHTTP(w, r)
- })
- }
- func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("GET /me", func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, "you are admin")
- })
- srv := httptest.NewServer(logging(requireToken(mux)))
- defer srv.Close()
- for _, token := range []string{"", "Bearer secret"} {
- req, _ := http.NewRequest("GET", srv.URL+"/me", nil)
- if token != "" {
- req.Header.Set("Authorization", token)
- }
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- fmt.Println(err)
- continue
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Printf("status=%d body=%q\n", resp.StatusCode, body)
- }
- }
輸出:
- -> GET /me
- <- GET /me
- status=401 body="unauthorized\n"
- -> GET /me
- <- GET /me
- status=200 body="you are admin"
http.Server:設定逾時再啟動
http.ListenAndServe(":8080", mux) 很方便,但它用的 Server 沒有任何逾時:慢速用戶端可以一直佔住連線不放(Slowloris 攻擊)。正式環境請自己建立 http.Server 並設定:| 欄位 | 限制什麼 |
|---|---|
ReadHeaderTimeout | 讀完請求標頭的時間,最重要的一項 |
ReadTimeout | 讀完整個請求(含內文)的時間 |
WriteTimeout | 從讀完標頭到寫完回應的時間 |
IdleTimeout | keep-alive 連線閒置多久後關閉 |
MaxHeaderBytes | 請求標頭的最大位元組數 |
啟動方式有
ListenAndServe()(自己開 port)或 Serve(listener)(用你已開好的 listener)。它們會一直阻塞,直到伺服器關閉,關閉時回傳 http.ErrServerClosed,這不是真正的錯誤,要特別排除。簽名:
- func (s *Server) ListenAndServe() error
- func (s *Server) Serve(l net.Listener) error
- func (s *Server) Close() error
注意:
WriteTimeout 會切斷長時間串流(例如 SSE),這類端點需要另外處理。範例:
- package main
- import (
- "errors"
- "fmt"
- "io"
- "net"
- "net/http"
- "time"
- )
- func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, "hello")
- })
- srv := &http.Server{
- Handler: mux,
- ReadHeaderTimeout: 5 * time.Second,
- ReadTimeout: 10 * time.Second,
- WriteTimeout: 10 * time.Second,
- IdleTimeout: 60 * time.Second,
- MaxHeaderBytes: 1 << 20,
- }
- ln, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- fmt.Println(err)
- return
- }
- done := make(chan error, 1)
- go func() { done <- srv.Serve(ln) }()
- resp, err := http.Get("http://" + ln.Addr().String() + "/hello")
- if err != nil {
- fmt.Println(err)
- return
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Println(resp.StatusCode, string(body))
- srv.Close()
- err = <-done
- fmt.Println("serve returned:", err, errors.Is(err, http.ErrServerClosed))
- }
輸出:
- 200 hello
- serve returned: http: Server closed true
Server.Shutdown:優雅關閉
Close 會立刻切斷所有連線,正在處理的請求直接失敗。Shutdown 則是「優雅關閉(graceful shutdown)」:先停止接新連線,再等進行中的請求處理完,最後關閉閒置連線。傳入的 context 決定最多等多久,逾時就回傳 context 的錯誤。實務上通常搭配 os/signal 在收到 Ctrl+C 時呼叫。RegisterOnShutdown 可以註冊關閉時要執行的函式。簽名:
- func (s *Server) Shutdown(ctx context.Context) error
- func (s *Server) RegisterOnShutdown(f func())
注意:呼叫
Shutdown 後,Serve 會立刻回傳 ErrServerClosed。如果 main 在那時就結束,進行中的請求一樣會被中斷,所以要等 Shutdown 回傳後才讓程式退出。範例:
- package main
- import (
- "context"
- "errors"
- "fmt"
- "io"
- "net"
- "net/http"
- "time"
- )
- func main() {
- started := make(chan struct{})
- mux := http.NewServeMux()
- mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
- close(started)
- time.Sleep(300 * time.Millisecond)
- fmt.Fprint(w, "slow job finished")
- })
- srv := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}
- srv.RegisterOnShutdown(func() { fmt.Println("shutdown hook") })
- ln, _ := net.Listen("tcp", "127.0.0.1:0")
- serveErr := make(chan error, 1)
- go func() { serveErr <- srv.Serve(ln) }()
- result := make(chan string, 1)
- go func() {
- resp, err := http.Get("http://" + ln.Addr().String() + "/slow")
- if err != nil {
- result <- err.Error()
- return
- }
- defer resp.Body.Close()
- b, _ := io.ReadAll(resp.Body)
- result <- string(b)
- }()
- <-started
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
- fmt.Println("shutdown:", srv.Shutdown(ctx))
- fmt.Println("client got:", <-result)
- fmt.Println("serve:", errors.Is(<-serveErr, http.ErrServerClosed))
- }
輸出:
- shutdown hook
- shutdown: <nil>
- client got: slow job finished
- serve: true
http.Client:送出請求並設定逾時
http.Get、http.Post 用的是 http.DefaultClient,它沒有逾時,對方不回應就永遠卡住。自己建立 &http.Client{Timeout: ...},這個時間涵蓋連線、送出、讀完回應內文的全程。Client 內部有連線池,可以安全地被多個 goroutine 共用,整個程式建立一個重複使用即可,不要每次請求都建新的。簽名:
- type Client struct {
- Transport RoundTripper
- CheckRedirect func(req *Request, via []*Request) error
- Jar CookieJar
- Timeout time.Duration
- }
- func (c *Client) Get(url string) (resp *Response, err error)
- func (c *Client) Do(req *Request) (*Response, error)
注意:
err == nil 時一定要 resp.Body.Close(),否則連線無法回到連線池而洩漏。非 2xx 狀態碼(404、500)不是 err,要自己檢查 resp.StatusCode。範例:
- package main
- import (
- "errors"
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "time"
- )
- func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("GET /fast", func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, "quick")
- })
- mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
- select {
- case <-time.After(2 * time.Second):
- case <-r.Context().Done():
- }
- })
- srv := httptest.NewServer(mux)
- defer srv.Close()
- client := &http.Client{Timeout: 200 * time.Millisecond}
- resp, err := client.Get(srv.URL + "/fast")
- if err != nil {
- fmt.Println(err)
- return
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Println(resp.StatusCode, string(body))
- _, err = client.Get(srv.URL + "/slow")
- var te interface{ Timeout() bool }
- fmt.Println("timeout:", errors.As(err, &te) && te.Timeout())
- }
輸出:
- 200 quick
- timeout: true
http.NewRequestWithContext:自訂請求
要用 PUT/DELETE、加標頭、或讓單一請求可以被取消,就自己建立
*Request 再交給 Client.Do。NewRequestWithContext 讓請求綁定一個 context:context 逾時或被取消,請求會立刻中止,Do 回傳的錯誤可用 errors.Is(err, context.DeadlineExceeded) 判斷。這比
Client.Timeout 更靈活:每個請求可以有不同期限,也能跟著上游的請求一起取消。方法名稱建議用 http.MethodPut 這類常數,避免打錯字。簽名:
- func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
範例:
- package main
- import (
- "context"
- "errors"
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "strings"
- "time"
- )
- func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("PUT /notes/{id}", func(w http.ResponseWriter, r *http.Request) {
- b, _ := io.ReadAll(r.Body)
- fmt.Fprintf(w, "note %s = %s (%s)", r.PathValue("id"), b, r.Header.Get("Content-Type"))
- })
- mux.HandleFunc("GET /wait", func(w http.ResponseWriter, r *http.Request) {
- select {
- case <-time.After(2 * time.Second):
- case <-r.Context().Done():
- }
- })
- srv := httptest.NewServer(mux)
- defer srv.Close()
- ctx, cancel := context.WithTimeout(context.Background(), time.Second)
- defer cancel()
- req, err := http.NewRequestWithContext(ctx, http.MethodPut, srv.URL+"/notes/9", strings.NewReader("buy milk"))
- if err != nil {
- fmt.Println(err)
- return
- }
- req.Header.Set("Content-Type", "text/plain")
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- fmt.Println(err)
- return
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Println(resp.StatusCode, string(body))
- short, cancel2 := context.WithTimeout(context.Background(), 100*time.Millisecond)
- defer cancel2()
- req2, _ := http.NewRequestWithContext(short, http.MethodGet, srv.URL+"/wait", nil)
- _, err = http.DefaultClient.Do(req2)
- fmt.Println("deadline:", errors.Is(err, context.DeadlineExceeded))
- }
輸出:
- 200 note 9 = buy milk (text/plain)
- 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 在記憶體中模擬檔案系統。簽名:
- func FileServerFS(root fs.FS) Handler
- func StripPrefix(prefix string, h Handler) Handler
範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "testing/fstest"
- )
- func main() {
- files := fstest.MapFS{
- "index.html": {Data: []byte("<h1>home</h1>")},
- "css/app.css": {Data: []byte("body{margin:0}")},
- }
- mux := http.NewServeMux()
- mux.Handle("GET /assets/", http.StripPrefix("/assets/", http.FileServerFS(files)))
- srv := httptest.NewServer(mux)
- defer srv.Close()
- for _, p := range []string{"/assets/css/app.css", "/assets/missing.txt"} {
- resp, err := http.Get(srv.URL + p)
- if err != nil {
- fmt.Println(err)
- continue
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Printf("%d %-24s %q\n", resp.StatusCode, resp.Header.Get("Content-Type"), body)
- }
- }
輸出:
- 200 text/css; charset=utf-8 "body{margin:0}"
- 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