-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #9 from panz3r/main
add Requests logger
- Loading branch information
Showing
8 changed files
with
226 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package util | ||
|
||
import ( | ||
"net" | ||
"net/http" | ||
"strings" | ||
) | ||
|
||
// Request.RemoteAddress contains port, which we want to remove i.e.: | ||
// "[::1]:58292" => "[::1]" | ||
func ipAddrFromRemoteAddr(s string) string { | ||
// return full string for IPv6 inputs wihtout port | ||
if strings.LastIndex(s, "]") == len(s)-1 { | ||
return s | ||
} | ||
|
||
idx := strings.LastIndex(s, ":") | ||
if idx == -1 { | ||
return s | ||
} | ||
|
||
return s[:idx] | ||
} | ||
|
||
// requestGetRemoteAddress returns ip address of the client making the request, | ||
// taking into account http proxies | ||
func requestGetRemoteAddress(r *http.Request) net.IP { | ||
hdr := r.Header | ||
|
||
hdrRealIP := hdr.Get("X-Real-Ip") | ||
hdrForwardedFor := hdr.Get("X-Forwarded-For") | ||
if hdrRealIP == "" && hdrForwardedFor == "" { | ||
return net.ParseIP(ipAddrFromRemoteAddr(r.RemoteAddr)) | ||
} | ||
|
||
if hdrForwardedFor != "" { | ||
// X-Forwarded-For is potentially a list of addresses separated with "," | ||
parts := strings.Split(hdrForwardedFor, ",") | ||
fwdIPs := make([]net.IP, len(parts)) | ||
for i, p := range parts { | ||
fwdIPs[i] = net.ParseIP(ipAddrFromRemoteAddr(strings.TrimSpace(p))) | ||
} | ||
// return first address | ||
return fwdIPs[0] | ||
} | ||
|
||
return net.ParseIP(hdrRealIP) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package util | ||
|
||
import ( | ||
"net/http" | ||
"testing" | ||
) | ||
|
||
func TestIPAddrFromRemoteAddr(t *testing.T) { | ||
tests := []struct { | ||
remoteAddr string | ||
expected string | ||
}{ | ||
{"[::1]:58292", "[::1]"}, | ||
{"127.0.0.1:12345", "127.0.0.1"}, | ||
{"[::1]", "[::1]"}, | ||
{"127.0.0.1", "127.0.0.1"}, | ||
} | ||
|
||
for _, tt := range tests { | ||
actual := ipAddrFromRemoteAddr(tt.remoteAddr) | ||
if actual != tt.expected { | ||
t.Errorf("ipAddrFromRemoteAddr(%s): expected %s, got %s", tt.remoteAddr, tt.expected, actual) | ||
} | ||
} | ||
} | ||
|
||
func TestRequestGetRemoteAddress(t *testing.T) { | ||
tests := []struct { | ||
headerRealIP string | ||
headerForwardedFor string | ||
remoteAddr string | ||
expected string | ||
}{ | ||
{"", "", "127.0.0.1:12345", "127.0.0.1"}, | ||
{"", "192.168.0.1, 127.0.0.1", "127.0.0.1:12345", "192.168.0.1"}, | ||
{"192.168.0.1", "", "127.0.0.1:12345", "192.168.0.1"}, | ||
{"192.168.0.1", "192.168.0.2, 127.0.0.1", "127.0.0.1:12345", "192.168.0.2"}, | ||
} | ||
|
||
for _, tt := range tests { | ||
req, _ := http.NewRequest("GET", "/", nil) | ||
req.Header.Set("X-Real-Ip", tt.headerRealIP) | ||
req.Header.Set("X-Forwarded-For", tt.headerForwardedFor) | ||
req.RemoteAddr = tt.remoteAddr | ||
|
||
actual := requestGetRemoteAddress(req) | ||
if actual.String() != tt.expected { | ||
t.Errorf("requestGetRemoteAddress(%s, %s, %s): expected %s, got %s", tt.headerRealIP, tt.headerForwardedFor, tt.remoteAddr, tt.expected, actual) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
package util | ||
|
||
import ( | ||
"net" | ||
"net/http" | ||
"os" | ||
"time" | ||
|
||
"github.com/felixge/httpsnoop" | ||
"github.com/rs/zerolog" | ||
"github.com/rs/zerolog/log" | ||
) | ||
|
||
type LogRequestHandlerOptions struct { | ||
Pretty bool | ||
} | ||
|
||
// LogReqInfo describes info about HTTP request | ||
type HTTPReqInfo struct { | ||
// GET etc. | ||
method string | ||
// requested path | ||
path string | ||
// response code, like 200, 404 | ||
code int | ||
// number of bytes of the response sent | ||
size int64 | ||
// how long did it take to | ||
duration time.Duration | ||
// client IP Address | ||
ipAddress net.IP | ||
// client UserAgent | ||
userAgent string | ||
// referer header | ||
referer string | ||
} | ||
|
||
func logHTTPReqInfo(ri *HTTPReqInfo) { | ||
log.Info(). | ||
Str("method", ri.method). | ||
Str("path", ri.path). | ||
Int("code", ri.code). | ||
Int64("size", ri.size). | ||
Dur("duration", ri.duration). | ||
IPAddr("ipAddress", ri.ipAddress). | ||
Str("userAgent", ri.userAgent). | ||
Str("referer", ri.referer). | ||
Send() | ||
} | ||
|
||
func LogRequestHandler(h http.Handler, opt *LogRequestHandlerOptions) http.Handler { | ||
if opt.Pretty { | ||
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) | ||
} | ||
|
||
zerolog.DurationFieldUnit = time.Millisecond | ||
|
||
fn := func(w http.ResponseWriter, r *http.Request) { | ||
// runs handler h and captures information about HTTP request | ||
mtr := httpsnoop.CaptureMetrics(h, w, r) | ||
|
||
logHTTPReqInfo(&HTTPReqInfo{ | ||
method: r.Method, | ||
path: r.URL.String(), | ||
code: mtr.Code, | ||
size: mtr.Written, | ||
duration: mtr.Duration, | ||
ipAddress: requestGetRemoteAddress(r), | ||
userAgent: r.Header.Get("User-Agent"), | ||
referer: r.Header.Get("Referer"), | ||
}) | ||
} | ||
|
||
return http.HandlerFunc(fn) | ||
} |