net/http/httputil

最後更新


net/http/httputil 提供 HTTP 的進階工具,最常用的是反向代理 ReverseProxy,以及把請求、回應印成原始文字的除錯函式。

這個套件做什麼


反向代理(reverse proxy)是站在後端伺服器前面的「櫃檯」:用戶端只跟代理說話,代理把請求轉給真正的後端,再把後端的回應交回給用戶端。常見用途:
  • API 閘道:統一入口,依路徑轉給不同服務
  • 隱藏後端:拿掉後端的 Server 標頭、加上內部金鑰
  • 本機開發:前端伺服器把 /api 轉給後端

httputil.ReverseProxy 本身就是一個 http.Handler,可以直接掛到 net/http 的路由上。
另一組工具 DumpRequest、DumpRequestOut、DumpResponse 把 HTTP 訊息印成線上傳輸的原始格式,除錯時很好用。
注意:這個套件裡的 ClientConn、ServerConn 與 ReverseProxy.Director 欄位都已棄用;本頁一律使用 Rewrite。

匯入


  1. import "net/http/httputil"

常用 API


ReverseProxy 與 Rewrite:轉發請求


建立 &httputil.ReverseProxy{Rewrite: ...}。Rewrite(Go 1.20 起)收到一個 *ProxyRequest,裡面有兩個請求:
欄位是什麼可以改嗎
pr.In用戶端送來的原始請求只讀
pr.Out即將送給後端的請求可以改

最常用的兩個方法:
  • pr.SetURL(target):把請求導向 target,並把 target 的路徑接在原路徑前面(/api + /users → /api/users),也會把 Host 標頭改成後端的主機
  • pr.SetXForwarded():加上 X-Forwarded-For、X-Forwarded-Host、X-Forwarded-Proto,讓後端知道原始用戶端是誰

簽名:
  1. type ReverseProxy struct {
  2. Rewrite func(*ProxyRequest)
  3. Transport http.RoundTripper
  4. ModifyResponse func(*http.Response) error
  5. ErrorHandler func(http.ResponseWriter, *http.Request, error)
  6. }
  7. func (r *ProxyRequest) SetURL(target *url.URL)
  8. func (r *ProxyRequest) SetXForwarded()

注意:使用 Rewrite 時,代理會先刪掉用戶端送來的 X-Forwarded-* 標頭,避免被偽造;要保留就要明確呼叫 SetXForwarded()。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "net/http/httputil"
  8. "net/url"
  9. )
  10. func main() {
  11. backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  12. fmt.Fprintf(w, "backend saw path=%s query=%s xff=%t", r.URL.Path, r.URL.RawQuery, r.Header.Get("X-Forwarded-For") != "")
  13. }))
  14. defer backend.Close()
  15. target, _ := url.Parse(backend.URL + "/api")
  16. proxy := &httputil.ReverseProxy{
  17. Rewrite: func(pr *httputil.ProxyRequest) {
  18. pr.SetURL(target)
  19. pr.SetXForwarded()
  20. },
  21. }
  22. front := httptest.NewServer(proxy)
  23. defer front.Close()
  24. resp, err := http.Get(front.URL + "/users?id=7")
  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. }

輸出:
  1. 200 backend saw path=/api/users query=id=7 xff=true

在 Rewrite 中改寫路徑與標頭


pr.Out 是一般的 *http.Request,所以可以自由調整:去掉路徑前綴、加上後端需要的金鑰、刪掉不該外流的標頭。修改要在 SetURL 之後,否則會被 SetURL 覆蓋。
簽名:
  1. type ProxyRequest struct {
  2. In *http.Request
  3. Out *http.Request
  4. }

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "net/http/httputil"
  8. "net/url"
  9. "strings"
  10. )
  11. func main() {
  12. backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  13. fmt.Fprintf(w, "path=%s key=%s hop=%q", r.URL.Path, r.Header.Get("X-Api-Key"), r.Header.Get("X-Debug"))
  14. }))
  15. defer backend.Close()
  16. target, _ := url.Parse(backend.URL)
  17. proxy := &httputil.ReverseProxy{
  18. Rewrite: func(pr *httputil.ProxyRequest) {
  19. pr.SetURL(target)
  20. pr.Out.URL.Path = strings.TrimPrefix(pr.In.URL.Path, "/gateway")
  21. pr.Out.Header.Set("X-Api-Key", "internal-key")
  22. pr.Out.Header.Del("X-Debug")
  23. },
  24. }
  25. front := httptest.NewServer(proxy)
  26. defer front.Close()
  27. req, _ := http.NewRequest("GET", front.URL+"/gateway/orders/3", nil)
  28. req.Header.Set("X-Debug", "1")
  29. resp, err := http.DefaultClient.Do(req)
  30. if err != nil {
  31. fmt.Println(err)
  32. return
  33. }
  34. body, _ := io.ReadAll(resp.Body)
  35. resp.Body.Close()
  36. fmt.Println(string(body))
  37. }

輸出:
  1. path=/orders/3 key=internal-key hop=""

ModifyResponse:改寫後端回應


ModifyResponse 在收到後端回應、送回用戶端之前被呼叫,可以改標頭、狀態碼甚至內文。回傳非 nil 錯誤時,代理會改走 ErrorHandler。
簽名:
  1. ModifyResponse func(*http.Response) error

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "net/http/httputil"
  8. "net/url"
  9. )
  10. func main() {
  11. backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  12. w.Header().Set("Server", "secret-backend/1.0")
  13. fmt.Fprint(w, "ok")
  14. }))
  15. defer backend.Close()
  16. target, _ := url.Parse(backend.URL)
  17. proxy := &httputil.ReverseProxy{
  18. Rewrite: func(pr *httputil.ProxyRequest) { pr.SetURL(target) },
  19. ModifyResponse: func(resp *http.Response) error {
  20. resp.Header.Del("Server")
  21. resp.Header.Set("X-Proxy", "gateway")
  22. return nil
  23. },
  24. }
  25. front := httptest.NewServer(proxy)
  26. defer front.Close()
  27. resp, err := http.Get(front.URL)
  28. if err != nil {
  29. fmt.Println(err)
  30. return
  31. }
  32. body, _ := io.ReadAll(resp.Body)
  33. resp.Body.Close()
  34. fmt.Printf("server=%q proxy=%q body=%s\n", resp.Header.Get("Server"), resp.Header.Get("X-Proxy"), body)
  35. }

輸出:
  1. server="" proxy="gateway" body=ok

ErrorHandler:後端連不上時怎麼回


後端掛掉或逾時,代理預設回 502 Bad Gateway 並把錯誤寫到 log。設定 ErrorHandler 可以自訂回覆內容,例如回一段 JSON 或記錄到自己的 log 系統。範例先開一個 port 再關掉,模擬一個連不上的後端。
簽名:
  1. ErrorHandler func(http.ResponseWriter, *http.Request, error)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "net/http"
  7. "net/http/httptest"
  8. "net/http/httputil"
  9. "net/url"
  10. )
  11. func main() {
  12. ln, _ := net.Listen("tcp", "127.0.0.1:0")
  13. deadAddr := ln.Addr().String()
  14. ln.Close()
  15. target, _ := url.Parse("http://" + deadAddr)
  16. proxy := &httputil.ReverseProxy{
  17. Rewrite: func(pr *httputil.ProxyRequest) { pr.SetURL(target) },
  18. ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
  19. http.Error(w, "upstream unavailable", http.StatusBadGateway)
  20. },
  21. }
  22. front := httptest.NewServer(proxy)
  23. defer front.Close()
  24. resp, err := http.Get(front.URL + "/anything")
  25. if err != nil {
  26. fmt.Println(err)
  27. return
  28. }
  29. body, _ := io.ReadAll(resp.Body)
  30. resp.Body.Close()
  31. fmt.Printf("%d %s", resp.StatusCode, body)
  32. }

輸出:
  1. 502 upstream unavailable

DumpRequest:印出伺服器收到的請求


在 Handler 裡呼叫 DumpRequest(r, true),會得到請求的原始文字:請求行、標頭、空行、內文。第二個參數 true 代表包含內文。
簽名:
  1. func DumpRequest(req *http.Request, body bool) ([]byte, error)

注意:包含內文時,函式會讀完 r.Body 再換成一份記憶體副本,後續程式仍可讀取;但內文很大時會整份放進記憶體。dump 內容可能含有密碼或 token,不要直接寫進正式環境的 log。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httptest"
  6. "net/http/httputil"
  7. "strings"
  8. )
  9. func main() {
  10. h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  11. dump, err := httputil.DumpRequest(r, true)
  12. if err != nil {
  13. http.Error(w, err.Error(), http.StatusInternalServerError)
  14. return
  15. }
  16. fmt.Printf("%s\n", dump)
  17. })
  18. req := httptest.NewRequest("POST", "/login", strings.NewReader("user=amy"))
  19. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  20. h.ServeHTTP(httptest.NewRecorder(), req)
  21. }

輸出:
  1. POST /login HTTP/1.1
  2. Host: example.com
  3. Content-Type: application/x-www-form-urlencoded
  4. user=amy

DumpRequestOut 與 DumpResponse:印出用戶端送出的請求與回應


DumpRequestOut 用在用戶端要送出的請求,會補上 Transport 實際會加的標頭(User-Agent、Accept-Encoding 等),讓你看到真正上線的內容;它不會真的把請求送到網路上。DumpResponse 印出一個 *http.Response。
簽名:
  1. func DumpRequestOut(req *http.Request, body bool) ([]byte, error)
  2. func DumpResponse(resp *http.Response, body bool) ([]byte, error)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httptest"
  6. "net/http/httputil"
  7. "strings"
  8. )
  9. func main() {
  10. req, _ := http.NewRequest("PUT", "http://api.example.com/items/1", strings.NewReader(`{"n":1}`))
  11. req.Header.Set("Content-Type", "application/json")
  12. out, err := httputil.DumpRequestOut(req, true)
  13. if err != nil {
  14. fmt.Println(err)
  15. return
  16. }
  17. fmt.Printf("%s\n---\n", out)
  18. rec := httptest.NewRecorder()
  19. rec.Header().Set("Content-Type", "text/plain")
  20. rec.WriteHeader(http.StatusTeapot)
  21. rec.WriteString("short and stout")
  22. resp := rec.Result()
  23. dump, err := httputil.DumpResponse(resp, true)
  24. if err != nil {
  25. fmt.Println(err)
  26. return
  27. }
  28. fmt.Printf("%s\n", dump)
  29. }

輸出:
  1. PUT /items/1 HTTP/1.1
  2. Host: api.example.com
  3. User-Agent: Go-http-client/1.1
  4. Content-Length: 7
  5. Content-Type: application/json
  6. Accept-Encoding: gzip
  7. {"n":1}
  8. ---
  9. HTTP/1.1 418 I'm a teapot
  10. Connection: close
  11. Content-Type: text/plain
  12. short and stout

重點整理


  • ReverseProxy 是 http.Handler,用 Rewrite 設定轉發規則;Director 已棄用
  • Rewrite 中 pr.In 只讀、pr.Out 可改;先 SetURL 再改其他欄位
  • 需要轉發用戶端資訊就呼叫 SetXForwarded()
  • ModifyResponse 改回應、ErrorHandler 處理後端錯誤
  • 除錯用 DumpRequest(伺服器端)、DumpRequestOut(用戶端)、DumpResponse;注意敏感資料

資料來源