diff --git a/http/main.go b/http/main.go new file mode 100644 index 0000000..58d5503 --- /dev/null +++ b/http/main.go @@ -0,0 +1,11 @@ +package http + +import "net/http" + +func GetRemoteIP(r *http.Request) string { + ip := r.Header.Get("X-Forwarded-For") + if len(ip) <= 1 { + ip = r.RemoteAddr + } + return ip +} diff --git a/http/main_test.go b/http/main_test.go new file mode 100644 index 0000000..91034b7 --- /dev/null +++ b/http/main_test.go @@ -0,0 +1,19 @@ +package http + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/assert" +) + +// Function to test the logging +// Input: pointer to teh testing object +func TestGetIP(t *testing.T) { + assertion := assert.New(t) + + req, _ := http.NewRequest("GET", "https://google.com/lola/duda?q=wasd", nil) + ip := GetRemoteIP(req) + + assertion.Equal("", ip, "no remote ip address") +} diff --git a/log/main.go b/log/main.go index 6a4604f..ef8d616 100644 --- a/log/main.go +++ b/log/main.go @@ -6,6 +6,7 @@ import ( "net/http" logger "github.com/Sirupsen/logrus" + httpLib "github.com/genofire/golang-lib/http" ) // Current logger with it's configuration @@ -20,12 +21,8 @@ func init() { // Function to add the information of a http request to the log func HTTP(r *http.Request) *logger.Entry { - ip := r.Header.Get("X-Forwarded-For") - if len(ip) <= 1 { - ip = r.RemoteAddr - } return Log.WithFields(logger.Fields{ - "remote": ip, + "remote": httpLib.GetRemoteIP(r), "method": r.Method, "url": r.URL.RequestURI(), })