我一直在想是否已经有一种方法可以将所有http/Response
都写入[]byte
?我发现有答复指出,可以通过执行[]byte
轻松地将主体转换为ioutil.ReadAll(response.Body)
,但是是否存在一种已经构建好的解决方案,可以写入所有信息(包括状态码, header ,尾部等)?
我问的原因是因为我希望通过套接字将整个响应传输到客户端,并且Write
库的net
方法需要一个字节数组。
最佳答案
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"
关于go - 是否有Go http方法将整个http响应转换为 byte slice ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64897956/