From 34141ee2b023dc13ee7d8e4ca50538a967476668 Mon Sep 17 00:00:00 2001 From: Martin Geno Date: Mon, 29 May 2017 22:53:51 +0200 Subject: [PATCH] [TASK] http add GetRemoteIP --- http/main.go | 11 +++++++++++ http/main_test.go | 19 +++++++++++++++++++ log/main.go | 7 ++----- 3 files changed, 32 insertions(+), 5 deletions(-) create mode 100644 http/main.go create mode 100644 http/main_test.go 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(), })