是否有一种 Go http 方法可以将整个 http 响应转换为字节片?

Is there a Go http method that converts an entire http response to a byte slice?

一直在想有没有办法把一个http/Response全部写成一个[]byte?我发现响应指出 body 可以通过执行 ioutil.ReadAll(response.Body) 轻松转换为 []byte,但是是否有一个 already-built 解决方案可以写入所有信息(包括状态代码、headers、预告片等)?

我问的原因是因为我希望通过套接字将整个响应传输到客户端,而 net 库的 Write 方法需要一个字节数组。

httputil.DumpResponse 是您所需要的(Adrian 也建议)。以下代码应该有所帮助:

package main

import (
    "fmt"
    "net/http"
    "net/http/httptest"
    "net/http/httputil"
    "os"
)

func main() {
    // Create a test server
    server := httptest.NewServer(http.HandlerFunc(
        func(w http.ResponseWriter, r *http.Request) {
            // Set Header
            w.Header().Set("HEADER_KEY", "HEADER_VALUE")
            // Set Response Body
            fmt.Fprintln(w, "DUMMY_BODY")
        }))
    defer server.Close()

    // Request to the test server
    resp, err := http.Get(server.URL)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    defer resp.Body.Close()

    // DumpResponse takes two parameters: (resp *http.Response, body bool)
    // where resp is the pointer to the response object. And body is boolean
    // to dump body or not
    dump, err := httputil.DumpResponse(resp, true)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    // Dump the response ([]byte)
    fmt.Printf("%q", dump)
}

输出:

"HTTP/1.1 200 OK\r\nContent-Length: 11\r\nContent-Type: text/plain; charset=utf-8\r\n
Date: Wed, 18 Nov 2020 17:43:40 GMT\r\n
Header_key: HEADER_VALUE\r\n\r\n
DUMMY_BODY\n"