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。匯入
- 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,讓後端知道原始用戶端是誰
簽名:
- type ReverseProxy struct {
- Rewrite func(*ProxyRequest)
- Transport http.RoundTripper
- ModifyResponse func(*http.Response) error
- ErrorHandler func(http.ResponseWriter, *http.Request, error)
- }
- func (r *ProxyRequest) SetURL(target *url.URL)
- func (r *ProxyRequest) SetXForwarded()
注意:使用
Rewrite 時,代理會先刪掉用戶端送來的 X-Forwarded-* 標頭,避免被偽造;要保留就要明確呼叫 SetXForwarded()。範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "net/http/httputil"
- "net/url"
- )
- func main() {
- backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintf(w, "backend saw path=%s query=%s xff=%t", r.URL.Path, r.URL.RawQuery, r.Header.Get("X-Forwarded-For") != "")
- }))
- defer backend.Close()
- target, _ := url.Parse(backend.URL + "/api")
- proxy := &httputil.ReverseProxy{
- Rewrite: func(pr *httputil.ProxyRequest) {
- pr.SetURL(target)
- pr.SetXForwarded()
- },
- }
- front := httptest.NewServer(proxy)
- defer front.Close()
- resp, err := http.Get(front.URL + "/users?id=7")
- if err != nil {
- fmt.Println(err)
- return
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Println(resp.StatusCode, string(body))
- }
輸出:
- 200 backend saw path=/api/users query=id=7 xff=true
在 Rewrite 中改寫路徑與標頭
pr.Out 是一般的 *http.Request,所以可以自由調整:去掉路徑前綴、加上後端需要的金鑰、刪掉不該外流的標頭。修改要在 SetURL 之後,否則會被 SetURL 覆蓋。簽名:
- type ProxyRequest struct {
- In *http.Request
- Out *http.Request
- }
範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "net/http/httputil"
- "net/url"
- "strings"
- )
- func main() {
- backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintf(w, "path=%s key=%s hop=%q", r.URL.Path, r.Header.Get("X-Api-Key"), r.Header.Get("X-Debug"))
- }))
- defer backend.Close()
- target, _ := url.Parse(backend.URL)
- proxy := &httputil.ReverseProxy{
- Rewrite: func(pr *httputil.ProxyRequest) {
- pr.SetURL(target)
- pr.Out.URL.Path = strings.TrimPrefix(pr.In.URL.Path, "/gateway")
- pr.Out.Header.Set("X-Api-Key", "internal-key")
- pr.Out.Header.Del("X-Debug")
- },
- }
- front := httptest.NewServer(proxy)
- defer front.Close()
- req, _ := http.NewRequest("GET", front.URL+"/gateway/orders/3", nil)
- req.Header.Set("X-Debug", "1")
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- fmt.Println(err)
- return
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Println(string(body))
- }
輸出:
- path=/orders/3 key=internal-key hop=""
ModifyResponse:改寫後端回應
ModifyResponse 在收到後端回應、送回用戶端之前被呼叫,可以改標頭、狀態碼甚至內文。回傳非 nil 錯誤時,代理會改走 ErrorHandler。簽名:
- ModifyResponse func(*http.Response) error
範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "net/http/httputil"
- "net/url"
- )
- func main() {
- backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Server", "secret-backend/1.0")
- fmt.Fprint(w, "ok")
- }))
- defer backend.Close()
- target, _ := url.Parse(backend.URL)
- proxy := &httputil.ReverseProxy{
- Rewrite: func(pr *httputil.ProxyRequest) { pr.SetURL(target) },
- ModifyResponse: func(resp *http.Response) error {
- resp.Header.Del("Server")
- resp.Header.Set("X-Proxy", "gateway")
- return nil
- },
- }
- front := httptest.NewServer(proxy)
- defer front.Close()
- resp, err := http.Get(front.URL)
- if err != nil {
- fmt.Println(err)
- return
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Printf("server=%q proxy=%q body=%s\n", resp.Header.Get("Server"), resp.Header.Get("X-Proxy"), body)
- }
輸出:
- server="" proxy="gateway" body=ok
ErrorHandler:後端連不上時怎麼回
後端掛掉或逾時,代理預設回
502 Bad Gateway 並把錯誤寫到 log。設定 ErrorHandler 可以自訂回覆內容,例如回一段 JSON 或記錄到自己的 log 系統。範例先開一個 port 再關掉,模擬一個連不上的後端。簽名:
- ErrorHandler func(http.ResponseWriter, *http.Request, error)
範例:
- package main
- import (
- "fmt"
- "io"
- "net"
- "net/http"
- "net/http/httptest"
- "net/http/httputil"
- "net/url"
- )
- func main() {
- ln, _ := net.Listen("tcp", "127.0.0.1:0")
- deadAddr := ln.Addr().String()
- ln.Close()
- target, _ := url.Parse("http://" + deadAddr)
- proxy := &httputil.ReverseProxy{
- Rewrite: func(pr *httputil.ProxyRequest) { pr.SetURL(target) },
- ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
- http.Error(w, "upstream unavailable", http.StatusBadGateway)
- },
- }
- front := httptest.NewServer(proxy)
- defer front.Close()
- resp, err := http.Get(front.URL + "/anything")
- if err != nil {
- fmt.Println(err)
- return
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Printf("%d %s", resp.StatusCode, body)
- }
輸出:
- 502 upstream unavailable
DumpRequest:印出伺服器收到的請求
在 Handler 裡呼叫
DumpRequest(r, true),會得到請求的原始文字:請求行、標頭、空行、內文。第二個參數 true 代表包含內文。簽名:
- func DumpRequest(req *http.Request, body bool) ([]byte, error)
注意:包含內文時,函式會讀完
r.Body 再換成一份記憶體副本,後續程式仍可讀取;但內文很大時會整份放進記憶體。dump 內容可能含有密碼或 token,不要直接寫進正式環境的 log。範例:
- package main
- import (
- "fmt"
- "net/http"
- "net/http/httptest"
- "net/http/httputil"
- "strings"
- )
- func main() {
- h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- dump, err := httputil.DumpRequest(r, true)
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
- fmt.Printf("%s\n", dump)
- })
- req := httptest.NewRequest("POST", "/login", strings.NewReader("user=amy"))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- h.ServeHTTP(httptest.NewRecorder(), req)
- }
輸出:
- POST /login HTTP/1.1
- Host: example.com
- Content-Type: application/x-www-form-urlencoded
- user=amy
DumpRequestOut 與 DumpResponse:印出用戶端送出的請求與回應
DumpRequestOut 用在用戶端要送出的請求,會補上 Transport 實際會加的標頭(User-Agent、Accept-Encoding 等),讓你看到真正上線的內容;它不會真的把請求送到網路上。DumpResponse 印出一個 *http.Response。簽名:
- func DumpRequestOut(req *http.Request, body bool) ([]byte, error)
- func DumpResponse(resp *http.Response, body bool) ([]byte, error)
範例:
- package main
- import (
- "fmt"
- "net/http"
- "net/http/httptest"
- "net/http/httputil"
- "strings"
- )
- func main() {
- req, _ := http.NewRequest("PUT", "http://api.example.com/items/1", strings.NewReader(`{"n":1}`))
- req.Header.Set("Content-Type", "application/json")
- out, err := httputil.DumpRequestOut(req, true)
- if err != nil {
- fmt.Println(err)
- return
- }
- fmt.Printf("%s\n---\n", out)
- rec := httptest.NewRecorder()
- rec.Header().Set("Content-Type", "text/plain")
- rec.WriteHeader(http.StatusTeapot)
- rec.WriteString("short and stout")
- resp := rec.Result()
- dump, err := httputil.DumpResponse(resp, true)
- if err != nil {
- fmt.Println(err)
- return
- }
- fmt.Printf("%s\n", dump)
- }
輸出:
- PUT /items/1 HTTP/1.1
- Host: api.example.com
- User-Agent: Go-http-client/1.1
- Content-Length: 7
- Content-Type: application/json
- Accept-Encoding: gzip
- {"n":1}
- ---
- HTTP/1.1 418 I'm a teapot
- Connection: close
- Content-Type: text/plain
- short and stout
重點整理
ReverseProxy是http.Handler,用Rewrite設定轉發規則;Director已棄用Rewrite中pr.In只讀、pr.Out可改;先SetURL再改其他欄位- 需要轉發用戶端資訊就呼叫
SetXForwarded() ModifyResponse改回應、ErrorHandler處理後端錯誤- 除錯用
DumpRequest(伺服器端)、DumpRequestOut(用戶端)、DumpResponse;注意敏感資料