是否有将整个 http 响应转换为字节切片的 Go http 方法?

我一直想知道是否已经有一种方法可以将所有的 a 写入http/Response[]byte?我发现响应指出,body 可以通过 do 轻松转换为 a []byteioutil.ReadAll(response.Body)但是是否有一个已经构建的解决方案可以写入所有信息(包括状态代码、标题、预告片等)?

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


跃然一笑
浏览 368回答 1
1回答

慕的地6264312

httputil.DumpResponse是您所需要的(也由 Adrian 建议)。以下代码应该会有所帮助:package mainimport (    "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\nDate: Wed, 18 Nov 2020 17:43:40 GMT\r\nHeader_key: HEADER_VALUE\r\n\r\nDUMMY_BODY\n"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go