realips: better logging and fail back to ""
Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
This commit is contained in:
parent
ea6b44a78c
commit
48732a6ea0
1 changed files with 13 additions and 5 deletions
18
httplog.go
18
httplog.go
|
@ -2,9 +2,12 @@ package httplog
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
@ -65,21 +68,26 @@ func LogRequest(r *http.Request, statusCode int) {
|
||||||
|
|
||||||
func RealIP(r *http.Request) string {
|
func RealIP(r *http.Request) string {
|
||||||
rip := RealIPs(r)
|
rip := RealIPs(r)
|
||||||
|
if len(rip) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
return rip[len(rip)-1]
|
return rip[len(rip)-1]
|
||||||
}
|
}
|
||||||
|
|
||||||
func RealIPs(r *http.Request) (ips []string) {
|
func RealIPs(r *http.Request) (ips []string) {
|
||||||
ip := r.RemoteAddr
|
logrus.Infof("httplog: RemoteAddr: %q", r.RemoteAddr)
|
||||||
|
ip, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||||
port_pos := strings.LastIndex(ip, ":")
|
if err != nil {
|
||||||
if port_pos != -1 {
|
logrus.Errorf("httplog: %q", err)
|
||||||
ip = ip[0:port_pos]
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if ip != "" {
|
if ip != "" {
|
||||||
ips = append(ips, ip)
|
ips = append(ips, ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
val := r.Header.Get("X-Forwarded-For")
|
val := r.Header.Get("X-Forwarded-For")
|
||||||
|
logrus.Infof("httplog: X-Forwarded-For: %q", val)
|
||||||
if val != "" {
|
if val != "" {
|
||||||
for _, ip := range strings.Split(val, ", ") {
|
for _, ip := range strings.Split(val, ", ") {
|
||||||
ips = append(ips, ip)
|
ips = append(ips, ip)
|
||||||
|
|
Loading…
Reference in a new issue