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

Add Special Regex for http_x_forwarded_for Var #37

Closed
wants to merge 2 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
23 changes: 21 additions & 2 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,30 @@ type Parser struct {
regexp *regexp.Regexp
}

func getSpecialNginxRegexes() map[string]string {
return map[string]string{
"http_x_forwarded_for": `[^ ]*(, [^ ]+)*`,
"remote_user": `[^"]*`}
}

// 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