clair/api/httputil/httputil.go
Sida Chen c6f0eaa3c8 api: fix remote addr shows reverse proxy addr problem
Uses the first ip addr in X-forwarded-for as the client's remote addr if it exists
otherwise, fall back to use default http.Request.RemoteAddr
2017-06-16 10:08:58 -04:00

25 lines
532 B
Go

package httputil
import (
"net"
"net/http"
"strings"
)
// GetClientAddr returns the first value in X-Forwarded-For if it exists
// otherwise fall back to use RemoteAddr
func GetClientAddr(r *http.Request) string {
addr := r.RemoteAddr
if s := r.Header.Get("X-Forwarded-For"); s != "" {
ips := strings.Split(s, ",")
// assume the first one is the client address
if len(ips) != 0 {
// validate the ip
if realIP := net.ParseIP(ips[0]); realIP != nil {
addr = strings.TrimSpace(ips[0])
}
}
}
return addr
}