53 lines
1.1 KiB
Go
Raw Normal View History

2019-04-26 10:11:17 +03:00
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package metrics
import (
"fmt"
)
// Parser keep tracks of the parsing
type Parser struct {
lines int // number of parsed lines (for the error messages)
lerr error // the last error occurred
}
2019-04-26 21:32:20 +03:00
// Parsed wraps a result for generating a parser error
2019-04-26 10:11:17 +03:00
type Parsed struct {
result // use struct embedding
err error // inject an error
}
// NewParser returns a new parser
func NewParser() *Parser {
return new(Parser)
}
// Parse parses a log line and returns a result with an injected error
2019-04-26 10:28:06 +03:00
func (p *Parser) Parse(line string) (parsed Parsed) {
2019-04-26 10:11:17 +03:00
// always set the error
2019-04-26 10:28:06 +03:00
defer func() { parsed.err = p.lerr }()
2019-04-26 10:11:17 +03:00
// if there was an error do not continue
2019-04-26 10:28:06 +03:00
if p.lerr != nil {
2019-04-26 10:11:17 +03:00
return
}
// chain the parser's error to the result's
res, err := parse(line)
2019-04-26 10:28:06 +03:00
if p.lines++; err != nil {
p.lerr = fmt.Errorf("%s: (line #%d)", err, p.lines)
2019-04-26 10:11:17 +03:00
}
return Parsed{result: res}
}
// Err returns the last error encountered
2019-04-26 10:28:06 +03:00
func (p *Parser) Err() error {
return p.lerr
2019-04-26 10:11:17 +03:00
}