Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor: Improve Code Readability with Constants and Early Returns #842

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 23 additions & 14 deletions middleware/realip.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ import (
"strings"
)

var trueClientIP = http.CanonicalHeaderKey("True-Client-IP")
var xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
var xRealIP = http.CanonicalHeaderKey("X-Real-IP")
const (
trueClientIP = "True-Client-IP"
xForwardedFor = "X-Forwarded-For"
xRealIP = "X-Real-IP"
)

// RealIP is a middleware that sets a http.Request's RemoteAddr to the results
// of parsing either the True-Client-IP, X-Real-IP or the X-Forwarded-For headers
Expand Down Expand Up @@ -40,21 +42,28 @@ func RealIP(h http.Handler) http.Handler {
}

func realIP(r *http.Request) string {
var ip string
if tcip := r.Header.Get(trueClientIP); isValidIP(tcip) {
return tcip
}

if tcip := r.Header.Get(trueClientIP); tcip != "" {
ip = tcip
} else if xrip := r.Header.Get(xRealIP); xrip != "" {
ip = xrip
} else if xff := r.Header.Get(xForwardedFor); xff != "" {
if xrip := r.Header.Get(xRealIP); isValidIP(xrip) {
return xrip
}

if xff := r.Header.Get(xForwardedFor); xff != "" {
i := strings.Index(xff, ",")
if i == -1 {
i = len(xff)
}
ip = xff[:i]
}
if ip == "" || net.ParseIP(ip) == nil {
return ""

if xff = xff[:i]; isValidIP(xff) {
return xff
}
}
return ip

return ""
}

func isValidIP(ip string) bool {
return ip != "" && net.ParseIP(ip) != nil
}