Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

refactoring: ClientIP extraction logic (#556)

Cooper Filbyab6a3c6074a1
diff --git a/app/pkg/web/request.go b/app/pkg/web/request.go
index 73121f42c..7e41b3216 100644
--- a/app/pkg/web/request.go
+++ b/app/pkg/web/request.go
@@ -2,6 +2,7 @@ package web
import (
"io/ioutil"
+ "net"
"net/http"
"net/url"
"strings"
@@ -46,12 +47,7 @@ func WrapRequest(request *http.Request) Request {
}
}
- clientIP := request.Header.Get("X-Forwarded-For")
- if clientIP == "" {
- clientIP = strings.Split(request.RemoteAddr, ":")[0]
- } else {
- clientIP = strings.Split(clientIP, ",")[0]
- }
+ clientIP := getClientIP(request)
return Request{
instance: request,
@@ -64,6 +60,16 @@ func WrapRequest(request *http.Request) Request {
}
}
+// getClientIP returns the IP of the original requestor.
+func getClientIP(request *http.Request) (clientIP string) {
+ if forwardedHosts := request.Header.Get("X-Forwarded-For"); forwardedHosts != "" {
+ clientIP = strings.Split(forwardedHosts, ",")[0]
+ } else {
+ clientIP, _, _ = net.SplitHostPort(request.RemoteAddr)
+ }
+ return
+}
+
// GetHeader returns the value of HTTP header from given key
func (r *Request) GetHeader(key string) string {
return r.instance.Header.Get(key)