-
Notifications
You must be signed in to change notification settings - Fork 18
/
parser.go
64 lines (54 loc) · 1.17 KB
/
parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
package iplibrary
import (
"bytes"
"errors"
)
type Parser struct {
config *ParserConfig
data []byte
}
func NewParser(config *ParserConfig) (*Parser, error) {
if config == nil {
config = &ParserConfig{}
}
if config.Template == nil {
return nil, errors.New("template must not be nil")
}
return &Parser{
config: config,
}, nil
}
func (this *Parser) Write(data []byte) {
this.data = append(this.data, data...)
}
func (this *Parser) Parse() error {
if len(this.data) == 0 {
return nil
}
for {
var index = bytes.IndexByte(this.data, '\n')
if index >= 0 {
var line = this.data[:index+1]
values, found := this.config.Template.Extract(string(line), this.config.EmptyValues)
if found {
if this.config.Iterator != nil {
err := this.config.Iterator(values)
if err != nil {
return err
}
}
} else {
// 防止错误信息太长
if len(line) > 256 {
line = line[:256]
}
return errors.New("invalid line '" + string(line) + "'")
}
this.data = this.data[index+1:]
} else {
break
}
}
return nil
}