realips: better logging and fail back to ""

Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
This commit is contained in:
Vincent Batts 2017-03-22 14:27:05 -04:00
parent ea6b44a78c
commit 48732a6ea0
Signed by: vbatts
GPG key ID: 10937E57733F1362

View file

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