Golang Read HTTP Header

Kevin FOO
Dec 9, 2020

The example below uses gorilla/mux package

package main

import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)

func YourHandler(w http.ResponseWriter, r *http.Request) {
for i,v := range r.Header {
fmt.Println(i, v)
}
fmt.Fprintf(w, r.Header.Get("User-Agent"))
}

func main() {
r := mux.NewRouter()
r.HandleFunc("/", YourHandler)
log.Fatal(http.ListenAndServe(":8000", r))
}

With the codes above, try browsing it with this URL with your browser

http://localhost:8000

Your web server console will print all the HTTP headers, similar like the screenshot below.

Web browser will show the user agent.

< Back to all the stories I had written

--

--

Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.