Skip to content

Commit

Permalink
Add Special Regex for http_x_forwarded_for Var
Browse files Browse the repository at this point in the history
Since there's the possibility for the http_x_forwarded_for Nginx
variable to contain a space (right after the comma separating two IP
addresses), create a regex for handling this variable. Change the way
the Nginx format regex is created by adding logic for including special
regexes.

Fixes #36

Signed-off-by: Jason Rogena <jasonrogena@gmail.com>
  • Loading branch information
jasonrogena committed Jan 18, 2018
1 parent ccfdceb commit bb55cd2
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,29 @@ type Parser struct {
regexp *regexp.Regexp
}

func getSpecialNginxRegexes() map[string]string {
return map[string]string{
"http_x_forwarded_for": `.|([\d\.]+(\, [\d\.]+)*)`}
}

// NewParser returns a new Parser, use given log format to create its internal
// strings parsing regexp.
func NewParser(format string) *Parser {
re := regexp.MustCompile(`\\\$([a-z_]+)(\\?(.))`).ReplaceAllString(
regexp.QuoteMeta(format+" "), "(?P<$1>[^$3]*)$2")
formatRegex := regexp.MustCompile(`([^ ]*)\$([a-z_]+)([^ ]*)([ ]?)`)
specialNginxRegexes := getSpecialNginxRegexes()
fields := formatRegex.FindAllStringSubmatch(format+" ", -1)
re := formatRegex.ReplaceAllString(format+" ", "$2$4")
for _, field := range fields {
terminateChar := field[3]
if len([]rune(terminateChar)) == 0 {
terminateChar = field[4]
}
if specialRegex, found := specialNginxRegexes[field[2]]; found {
re = strings.Replace(re, field[2]+field[4], regexp.QuoteMeta(field[1])+"(?P<"+field[2]+">"+specialRegex+")"+regexp.QuoteMeta(field[3])+field[4], 1)
} else {
re = strings.Replace(re, field[2]+field[4], regexp.QuoteMeta(field[1])+"(?P<"+field[2]+">[^"+terminateChar+"]*)"+regexp.QuoteMeta(field[3]+field[4]), 1)
}
}
return &Parser{format, regexp.MustCompile(fmt.Sprintf("^%v", strings.Trim(re, " ")))}
}

Expand Down

0 comments on commit bb55cd2

Please sign in to comment.