These snippets are dedicated to using [`net/http`](https://pkg.go.dev/net/http#hdr-Servers) in the context of HTTP servers. Building an HTTP server is arguably Go's raison d'être, so I find myself reaching for these patterns pretty often.
## Printing a Raw HTTP Response
Printing an HTTP response is sometimes necessary. I don't advise doing this in production, at least not directly. The major use case is debugging or logging, and I don't recommend logging raw HTTP responses in production due to potential sensitive information exposure.
```go
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
)
func main() {
resp, err := http.Get("http://example.com")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
// Print the HTTP response
// The second argument to DumpResponse indicates whether to include the response body in the dump.
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
fmt.Println("Error dumping response:", err)
return
}
fmt.Println(string(dump))
}
```
The `httputil.DumpResponse` function creates a byte slice containing the HTTP response, which can then be printed or logged.