1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-24 20:14:31 +02:00

Fixed bug where IP address wasn't showing up in log files. Also added

some tests for the Logger middleware.
This commit is contained in:
Mark Bates 2015-10-21 16:39:51 -04:00
parent 38d3cb5730
commit b02e78b749
2 changed files with 42 additions and 18 deletions

View File

@ -15,13 +15,15 @@ func Logger() echo.MiddlewareFunc {
req := c.Request()
res := c.Response()
remoteAddr := req.RemoteAddr
var remoteAddr string
if ip := req.Header.Get(echo.XRealIP); ip != "" {
remoteAddr = ip
} else if ip = req.Header.Get(echo.XForwardedFor); ip != "" {
remoteAddr = ip
} else {
remoteAddr = req.RemoteAddr
remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
}
remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
start := time.Now()
if err := h(c); err != nil {

View File

@ -1,12 +1,15 @@
package middleware
import (
"bytes"
"errors"
"log"
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo"
"github.com/stretchr/testify/assert"
)
func TestLogger(t *testing.T) {
@ -16,23 +19,8 @@ func TestLogger(t *testing.T) {
rec := httptest.NewRecorder()
c := echo.NewContext(req, echo.NewResponse(rec), e)
// With X-Real-IP
req.Header.Add(echo.XRealIP, "127.0.0.1")
h := func(c *echo.Context) error {
return c.String(http.StatusOK, "test")
}
Logger()(h)(c)
// With X-Forwarded-For
req.Header.Del(echo.XRealIP)
req.Header.Add(echo.XForwardedFor, "127.0.0.1")
h = func(c *echo.Context) error {
return c.String(http.StatusOK, "test")
}
Logger()(h)(c)
// Status 2xx
h = func(c *echo.Context) error {
h := func(c *echo.Context) error {
return c.String(http.StatusOK, "test")
}
Logger()(h)(c)
@ -62,3 +50,37 @@ func TestLogger(t *testing.T) {
}
Logger()(h)(c)
}
func TestLogger_IPAddress(t *testing.T) {
buf := &bytes.Buffer{}
log.SetOutput(buf)
ip := "127.0.0.1"
e := echo.New()
req, _ := http.NewRequest(echo.GET, "/", nil)
rec := httptest.NewRecorder()
c := echo.NewContext(req, echo.NewResponse(rec), e)
h := func(c *echo.Context) error {
return c.String(http.StatusOK, "test")
}
mw := Logger()
// With X-Real-IP
req.Header.Add(echo.XRealIP, ip)
mw(h)(c)
assert.Contains(t, buf.String(), ip)
// With X-Forwarded-For
buf.Reset()
req.Header.Del(echo.XRealIP)
req.Header.Add(echo.XForwardedFor, ip)
mw(h)(c)
assert.Contains(t, buf.String(), ip)
// with req.RemoteAddr
buf.Reset()
mw(h)(c)
assert.Contains(t, buf.String(), ip)
}