forked from fiorix/go-web
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logs.go
46 lines (42 loc) · 925 Bytes
/
logs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package goweb
import (
"fmt"
"net/http"
"strings"
"time"
)
// LogRequest constructs Apache like log with request duration
func LogRequest(log func(string), req *http.Request, created time.Time, status, bytes int) {
username := "-"
if req.URL.User != nil {
if name := req.URL.User.Username(); name != "" {
username = name
}
}
elapsed := float64(time.Since(created)) / float64(time.Millisecond)
ip := GetClientIP(req)
log(fmt.Sprintf("%s - %s \"%s %s %s\" %d %dB \"%s\". %fms",
ip,
username,
req.Method,
req.RequestURI,
req.Proto,
status,
bytes,
req.UserAgent(),
elapsed))
}
// GetClientIP retrives request client IP
func GetClientIP(req *http.Request) string {
ip := req.Header.Get("X-Real-IP")
if ip == "" {
ip = req.Header.Get("X-Forwarded-For")
if ip == "" {
ip = req.RemoteAddr
}
}
if colon := strings.LastIndex(ip, ":"); colon != -1 {
ip = ip[:colon]
}
return ip
}