Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extracting X-Forwarded-For from connections in Golang
package main
import (
"fmt"
"log"
"net/http"
"strings"
)
func main() {
th := loggingMiddleware(http.HandlerFunc(handler))
mux := http.NewServeMux()
mux.Handle("/", th)
log.Fatal(http.ListenAndServe(":9000", mux))
}
func loggingMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
ipAddress := req.RemoteAddr
fwdAddress := req.Header.Get("X-Forwarded-For") // capitalisation doesn't matter
if fwdAddress != "" {
// Got X-Forwarded-For
ipAddress = fwdAddress // If it's a single IP, then awesome!
// If we got an array... grab the first IP
ips := strings.Split(fwdAddress, ", ")
if len(ips) > 1 {
ipAddress = ips[0]
}
}
log.Println("Got connection from ", ipAddress)
h.ServeHTTP(rw, req)
})
}
func handler(w http.ResponseWriter, r *http.Request) {
log.Println("Here!")
fmt.Fprintf(w, "Sup dawgs")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.