I have been wondering if there is already a method to write all of an http/Response
into a []byte
? I've found responses that note that the body can be converted easily into a []byte
by doing ioutil.ReadAll(response.Body)
, but is there an already-built solution that writes all of the information (including status codes, headers, trailers, etc.)?
The reason I ask is because I wish to transmit this entire response through a socket to a client, and the Write
method of the net
library requires a byte array.
httputil.DumpResponse is what you need (Also suggested by Adrian). The following code should help:
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)
}
Output:
"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"