Go: Dump HTTP Request

Recently, I was implementing a Webhook for Gogs in Go. Unfortunately, the documentation is not one hundred percent complete and could be a bit more specific at times.

Also, neither reading Gogs source code nor other people’s implementation is what anyone really wants here.

What I ended up doing was dumping the complete request (including all HTTP Headers and Body) with the following, simple Go program:

package main

import (
	"fmt"
	"net/http"
	"net/http/httputil"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		dump, err := httputil.DumpRequest(r, true)
		if err == nil {
			fmt.Printf("%s\n", dump)
		} else {
			fmt.Printf("%s\n", err)
		}
		return
	})
	http.ListenAndServe(":8080", nil)
}

Instead of manually ranging over all values in the Header string map and doing all sorts of other stuff, simply use the DumpRequest function from the net/http/httputil package. There are also DumpRequestOut (for requests you are going to send out) and DumpResponse (for received responses) functions available.

Because these functions work with all HTTP versions, they are especially valuable for debugging HTTP/2 connections, since you get simple string output (instead of bytes).

Happy hacking!