🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## httputil ### httputil.DumpRequest 打印完整请求头 ``` func Api(w http.ResponseWriter, r *http.Request) { request, err := httputil.DumpRequest(r, true) if err != nil { http.Error(w, "asd", 200) } fmt.Printf("%q\n", request) io.WriteString(w, "ok") } ``` curl ``` curl -X POST -d "hello world" -i http://127.0.0.1:1234/api ``` 打印 ``` POST /api HTTP/1.1\r\nHost: 127.0.0.1:1234\r\nAccept: */*\r\nContent-Length: 11\r\nContent-Type: application/x-www-form-urlencoded\r\nUser-Agent: curl/7.55.1\r\n\r\nhello world ``` ### httputil.DumpResponse() 答应响应体 ``` // 模拟http server s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello") })) res, err := http.Get(s.URL) if err != nil { log.Fatal(err) } response, _ := httputil.DumpResponse(res, true) fmt.Printf("%q\n", response) // HTTP/1.1 200 OK\r\nContent-Length: 5\r\nContent-Type: text/plain; charset=utf-8\r\nDate: Mon, 28 Dec 2020 06:08:41 GMT\r\n\r\nhello ``` ### httputil.NewSingleHostReverseProxy 代理转发 ``` http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) { proxy, e := url.Parse("http://127.0.0.1:9092") if e != nil { panic(e) } reverseProxy := httputil.NewSingleHostReverseProxy(proxy) reverseProxy.ServeHTTP(w, r) }) ```