Skip to content

Commit

Permalink
updated IP address parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
irshadaj committed Jan 26, 2024
1 parent 840ae04 commit de31f8a
Showing 1 changed file with 21 additions and 19 deletions.
40 changes: 21 additions & 19 deletions cmd/api/src/api/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,33 +130,35 @@ func ContextMiddleware(next http.Handler) http.Handler {
requestCtx, cancel := context.WithTimeout(request.Context(), requestedWaitDuration.Value)
defer cancel()
// Insert the bh context
requestCtx = ctx.Set(requestCtx, &ctx.Context{
StartTime: startTime,
Timeout: requestedWaitDuration,
RequestID: requestID,
Host: &url.URL{
Scheme: getScheme(request),
Host: request.Host,
},
RequestIP: parseUserIP(request),
})
if ipAddress, err := parseUserIP(request); err != nil {
log.Errorf(err.Error())
} else {
requestCtx = ctx.Set(requestCtx, &ctx.Context{
StartTime: startTime,
Timeout: requestedWaitDuration,
RequestID: requestID,
Host: &url.URL{
Scheme: getScheme(request),
Host: request.Host,
},
RequestIP: ipAddress,
})
}

// Route the request with the embedded context
next.ServeHTTP(response, request.WithContext(requestCtx))
}
})
}

func parseUserIP(r *http.Request) string {
IPAddress := r.Header.Get("X-Forwarded-For")
if IPAddress == "" {
if parsedUrl, err := url.Parse(r.RemoteAddr); err != nil {
log.Errorf("error parsing IP address from RemoteAddr: %s", err)
} else {
IPAddress = parsedUrl.Hostname()
}
func parseUserIP(r *http.Request) (string, error) {
if ipAddress := r.Header.Get("X-Forwarded-For"); ipAddress != "" {
return strings.Split(ipAddress, " ")[0], nil
} else if parsedUrl, err := url.Parse(r.RemoteAddr); err != nil {
return "", fmt.Errorf("error parsing IP address from RemoteAddr: %s", err)
} else {
return parsedUrl.Hostname(), nil
}
return IPAddress
}

func ParseHeaderValues(values string) map[string]string {
Expand Down

0 comments on commit de31f8a

Please sign in to comment.