net/http/httptest
最後更新
net/http/httptest 讓你不必真的部署伺服器、也不必連外網,就能測試 HTTP Handler 與 HTTP 用戶端程式。這個套件做什麼
測 HTTP 程式有兩種情境,這個套件各給一套工具:
| 情境 | 工具 | 是否開真的 port |
|---|---|---|
| 測伺服器端 Handler:給它一個請求,看它回什麼 | NewRequest + NewRecorder | 否,直接呼叫函式 |
| 測用戶端程式:需要一個假的對方伺服器 | NewServer、NewTLSServer | 是,只聽 127.0.0.1 的隨機 port |
ResponseRecorder 最快,適合大量的表格驅動測試;httptest.Server 走完整的網路流程(連線、標頭解析、TLS),適合測 http.Client 的設定或第三方 API 的包裝程式。這些工具通常寫在
_test.go 裡(見單元測試)。為了讓範例可以直接 go run,本頁寫成 package main,用法在測試中完全相同。匯入
- import "net/http/httptest"
常用 API
NewRequest 與 NewRecorder:直接測 Handler
NewRecorder 建立一個 *ResponseRecorder,它實作 http.ResponseWriter,會把 Handler 寫的狀態碼、標頭、內文記錄下來。NewRequest 建立一個「像是伺服器收到的」請求。把兩者交給 Handler 呼叫一次,再檢查 rec.Code、rec.Header()、rec.Body。簽名:
- func NewRecorder() *ResponseRecorder
- func NewRequest(method, target string, body io.Reader) *http.Request
範例:
- package main
- import (
- "fmt"
- "net/http"
- "net/http/httptest"
- )
- func hello(w http.ResponseWriter, r *http.Request) {
- name := r.URL.Query().Get("name")
- if name == "" {
- http.Error(w, "name required", http.StatusBadRequest)
- return
- }
- w.Header().Set("Content-Type", "text/plain")
- fmt.Fprintf(w, "hello, %s", name)
- }
- func main() {
- for _, target := range []string{"/hello?name=Gopher", "/hello"} {
- req := httptest.NewRequest(http.MethodGet, target, nil)
- rec := httptest.NewRecorder()
- hello(rec, req)
- fmt.Printf("%d %q %q\n", rec.Code, rec.Header().Get("Content-Type"), rec.Body.String())
- }
- }
輸出:
- 200 "text/plain" "hello, Gopher"
- 400 "text/plain; charset=utf-8" "name required\n"
NewRequest 的預設值
target 可以只寫路徑,也可以寫完整網址。只寫路徑時,Host 預設為 example.com;RemoteAddr 固定是 192.0.2.1:1234(文件專用的保留位址);網址用 https 時會自動填上 r.TLS,讓 Handler 以為是 HTTPS 請求。傳入 strings.Reader 等內文時會自動設定 ContentLength。需要帶 context 時改用
NewRequestWithContext(Go 1.23 起)。簽名:
- func NewRequestWithContext(ctx context.Context, method, target string, body io.Reader) *http.Request
注意:
NewRequest 遇到不合法的 method 或 target 會直接 panic,因為它是給測試用的,不回傳錯誤。範例:
- package main
- import (
- "fmt"
- "net/http"
- "net/http/httptest"
- "strings"
- )
- func main() {
- req := httptest.NewRequest("POST", "/upload?dry=1", strings.NewReader("abc"))
- fmt.Println(req.Method, req.URL.Path, req.URL.RawQuery)
- fmt.Println("Host:", req.Host)
- fmt.Println("RemoteAddr:", req.RemoteAddr)
- fmt.Println("ContentLength:", req.ContentLength)
- req2 := httptest.NewRequest("GET", "https://api.example.com/v1", nil)
- fmt.Println(req2.Host, req2.TLS != nil)
- var h http.Handler = http.NotFoundHandler()
- rec := httptest.NewRecorder()
- h.ServeHTTP(rec, req2)
- fmt.Println(rec.Code)
- }
輸出:
- POST /upload dry=1
- Host: example.com
- RemoteAddr: 192.0.2.1:1234
- ContentLength: 3
- api.example.com true
- 404
ResponseRecorder.Result:取得完整的 http.Response
rec.Code、rec.Body 適合簡單檢查。要檢查 cookie、或把結果交給「吃 *http.Response 的函式」,呼叫 Result() 取得一個 *http.Response,用法跟真的用戶端收到的回應一樣。簽名:
- func (rw *ResponseRecorder) Result() *http.Response
注意:讀標頭請用
Result().Header 或 rec.Header();rec.HeaderMap 欄位已棄用。範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- )
- func main() {
- h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- http.SetCookie(w, &http.Cookie{Name: "session", Value: "s-1"})
- w.WriteHeader(http.StatusAccepted)
- io.WriteString(w, "queued")
- })
- rec := httptest.NewRecorder()
- h.ServeHTTP(rec, httptest.NewRequest("POST", "/jobs", nil))
- resp := rec.Result()
- defer resp.Body.Close()
- body, _ := io.ReadAll(resp.Body)
- fmt.Println(resp.Status)
- fmt.Println(string(body))
- for _, c := range resp.Cookies() {
- fmt.Println("cookie:", c.Name, c.Value)
- }
- }
輸出:
- 202 Accepted
- queued
- cookie: session s-1
NewServer:起一個本機假伺服器
NewServer 立刻在 127.0.0.1 的隨機 port 啟動一個真正的 HTTP 伺服器,srv.URL 是它的網址(例如 http://127.0.0.1:54321,port 每次不同)。把這個網址交給你的用戶端程式,就能測試完整的請求流程而不連外網。srv.Client() 回傳一個已設定好、可連到這台伺服器的 *http.Client。簽名:
- func NewServer(handler http.Handler) *Server
- func (s *Server) Client() *http.Client
- func (s *Server) Close()
注意:用完一定要
Close()(測試中寫 defer srv.Close()),它會等待所有進行中的請求結束。範例:
- package main
- import (
- "encoding/json"
- "fmt"
- "net/http"
- "net/http/httptest"
- "strings"
- )
- type weatherClient struct {
- baseURL string
- http *http.Client
- }
- func (c weatherClient) temp(city string) (float64, error) {
- resp, err := c.http.Get(c.baseURL + "/temp/" + city)
- if err != nil {
- return 0, err
- }
- defer resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- return 0, fmt.Errorf("status %d", resp.StatusCode)
- }
- var out struct {
- C float64 `json:"c"`
- }
- err = json.NewDecoder(resp.Body).Decode(&out)
- return out.C, err
- }
- func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("GET /temp/{city}", func(w http.ResponseWriter, r *http.Request) {
- if r.PathValue("city") != "taipei" {
- http.NotFound(w, r)
- return
- }
- w.Header().Set("Content-Type", "application/json")
- w.Write([]byte(`{"c":28.5}`))
- })
- srv := httptest.NewServer(mux)
- defer srv.Close()
- fmt.Println("local URL:", strings.HasPrefix(srv.URL, "http://127.0.0.1:"))
- c := weatherClient{baseURL: srv.URL, http: srv.Client()}
- fmt.Println(c.temp("taipei"))
- fmt.Println(c.temp("mars"))
- }
輸出:
- local URL: true
- 28.5 <nil>
- 0 status 404
NewTLSServer:測 HTTPS
NewTLSServer 與 NewServer 相同,但走 HTTPS,憑證是套件內建的自簽憑證。一般的 http.DefaultClient 不信任這張憑證,所以要用 srv.Client(),它已經設定成信任該憑證。簽名:
- func NewTLSServer(handler http.Handler) *Server
範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "strings"
- )
- func main() {
- srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintf(w, "tls=%v proto=%s", r.TLS != nil, r.Proto)
- }))
- defer srv.Close()
- fmt.Println(strings.HasPrefix(srv.URL, "https://"))
- resp, err := srv.Client().Get(srv.URL)
- if err != nil {
- fmt.Println(err)
- return
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Println(string(body))
- }
輸出:
- true
- tls=true proto=HTTP/1.1
NewUnstartedServer:先設定再啟動
想調整伺服器設定(例如開啟 HTTP/2、修改
http.Server 的欄位、關掉錯誤 log),用 NewUnstartedServer 建立但不啟動,改完 srv.Config(底層的 *http.Server)或 srv.EnableHTTP2 後,再呼叫 Start() 或 StartTLS()。範例開啟 HTTP/2,並把錯誤 log 導到
io.Discard,所以預設用戶端因為不信任憑證而握手失敗時,伺服器不會印出 log。簽名:
- func NewUnstartedServer(handler http.Handler) *Server
- func (s *Server) Start()
- func (s *Server) StartTLS()
範例:
- package main
- import (
- "fmt"
- "io"
- "log"
- "net/http"
- "net/http/httptest"
- )
- func main() {
- srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintf(w, "proto=%s", r.Proto)
- }))
- srv.EnableHTTP2 = true
- srv.Config.ErrorLog = log.New(io.Discard, "", 0)
- srv.StartTLS()
- defer srv.Close()
- resp, err := srv.Client().Get(srv.URL)
- if err != nil {
- fmt.Println(err)
- return
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Println(resp.StatusCode, string(body))
- _, err = http.Get(srv.URL)
- fmt.Println("default client fails:", err != nil)
- }
輸出:
- 200 proto=HTTP/2.0
- default client fails: true
重點整理
- 測 Handler:
NewRequest+NewRecorder,直接呼叫,最快 - 測用戶端:
NewServer起本機伺服器,把srv.URL交給被測程式,defer srv.Close() - HTTPS 用
NewTLSServer,並使用srv.Client() - 要自訂設定用
NewUnstartedServer,改完再Start/StartTLS - 檢查 cookie 或完整回應用
rec.Result();不要用已棄用的HeaderMap