Inspect HTTP Request and Response in Golang

Golang is getting popular for writing a web applications. One of the core concepts of this web application is handling requests and responses. In Golang, net/http package from the standard library provides all HTTP requests and responses mechanisms. 

As a developer, you often print this HTTP request or the response for debug purposes. net/http/httputil package has two excellent methods DumpRequest for printing pretty request. and DumpResponse methods for printing pretty response.  Let’s look at examples…

Example of httputil.DumpRequest :

requestDump, err := httputil.DumpRequest(req, true)
if err != nil {
fmt.Printf("%q", requestDump)


Accept: */*
Content-Length: 6
Content-Type: application/x-www-form-urlencoded
User-Agent: curl/7.71.1


It prints the whole request object. If you don’t want the body, change the boolean argument from true to false in httputil.DumpRequest().

You can also print only the body of the request. Just read the body from buffer. 

buf, err := ioutil.ReadAll(req.Body)
if err != nil {
	fmt.Println(err) //log it
fmt.Printf("%+v", string(buf))

Remember, you will have to write it back after reading it from the buffer; neither request will fail.

req.Body = ioutil.NopCloser(bytes.NewBuffer(buf))


Example of httputil.DumpResponse:

dumpResponse, err := httputil.DumpResponse(resp, true)
if err != nil {

fmt.Printf("%q", dumpResponse)


HTTP/1.1 200 OK
Accept-Ranges: bytes
Age: 357425
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Fri, 25 Feb 2022 06:48:03 GMT
Etag: "3247526947+gzip"
Expires: Fri, 04 May 2022 06:48:03 GMT
Last-Modified: Thu, 03 May 2022 07:18:26 GMT
Server: ECS (bsa/EB18)
Vary: Accept-Encoding
X-Cache: HIT

    <title>Example Domain</title> 
    <meta charset="utf-8" /> 
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> 
    <meta name="viewport" content="width=device-width, initial-scale=1" /> 

Eftakhairul Islam

Hi, I'm Eftakhairul Islam, a passionate Software Engineer, Hacker and Open Source Enthusiast. I enjoy writing about technical things, work in a couple of startup as a technical advisor and in my spare time, I contribute a lot of open source projects.


Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Read previous post:
Build SQL update query for HTTP Patch request in Golang

It seems pretty straightforward to implement HTTP Patch request. The handler receives the request, unmarshals the body, validates the payload,...