[TASK] http add GetRemoteIP

This commit is contained in:
Martin Geno 2017-05-29 22:53:51 +02:00
parent 63b322494e
commit 34141ee2b0
No known key found for this signature in database
GPG Key ID: F0D39A37E925E941
3 changed files with 32 additions and 5 deletions

11
http/main.go Normal file
View File

@ -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
}

19
http/main_test.go Normal file
View File

@ -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")
}

View File

@ -6,6 +6,7 @@ import (
"net/http" "net/http"
logger "github.com/Sirupsen/logrus" logger "github.com/Sirupsen/logrus"
httpLib "github.com/genofire/golang-lib/http"
) )
// Current logger with it's configuration // Current logger with it's configuration
@ -20,12 +21,8 @@ func init() {
// Function to add the information of a http request to the log // Function to add the information of a http request to the log
func HTTP(r *http.Request) *logger.Entry { 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{ return Log.WithFields(logger.Fields{
"remote": ip, "remote": httpLib.GetRemoteIP(r),
"method": r.Method, "method": r.Method,
"url": r.URL.RequestURI(), "url": r.URL.RequestURI(),
}) })