Created
January 18, 2017 04:45
-
-
Save 17twenty/c815680c9c585cd9c16e62cbee7317b6 to your computer and use it in GitHub Desktop.
Extracting X-Forwarded-For from connections in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
This is not a correct way of parsing X-Forwarded-For, the left most value is untrusted and can be spoofed in many situations.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
Here is a little snippet that will do it correctly, although you may need to add a configuration of how many trusted proxies are infront of your application