package main import ( "regexp" "strconv" "strings" "time" ) // Formato "combined" / "common" compartido por nginx y Apache: // 1.2.3.4 - user [10/Oct/2000:13:55:36 -0700] "GET /x HTTP/1.1" 200 2326 "ref" "ua" var logRe = regexp.MustCompile( `^(\S+) \S+ \S+ \[([^\]]+)\] "((?:[^"\\]|\\.)*)" (\d{3}) (\S+)(?: "((?:[^"\\]|\\.)*)" "((?:[^"\\]|\\.)*)")?`) const ( maxPathLen = 256 maxUALen = 200 ) func clip(s string, n int) string { if len(s) > n { s = s[:n] } // Clone para no retener la línea completa en memoria. return strings.Clone(s) } // ParseLine interpreta una línea de log. ok=false si no coincide con el formato. func ParseLine(line string) (c Conn, ok bool) { m := logRe.FindStringSubmatch(line) if m == nil { return c, false } c.IP = clip(m[1], 64) if t, err := time.Parse("02/Jan/2006:15:04:05 -0700", m[2]); err == nil { c.Time = t } else { c.Time = time.Now() } req := strings.SplitN(m[3], " ", 3) if len(req) >= 2 { c.Method = clip(req[0], 16) c.Path = clip(req[1], maxPathLen) } else { c.Path = clip(m[3], maxPathLen) } c.Status, _ = strconv.Atoi(m[4]) if m[5] != "-" { c.Bytes, _ = strconv.ParseInt(m[5], 10, 64) } if len(m) > 7 && m[7] != "" && m[7] != "-" { c.UA = clip(m[7], maxUALen) } return c, true }