-
Notifications
You must be signed in to change notification settings - Fork 43
/
line-reader.go
51 lines (45 loc) · 910 Bytes
/
line-reader.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
package utils
import (
"bufio"
"bytes"
"github.com/pkg/errors"
"os"
)
func RemoveBOM(raw []byte) []byte {
if len(raw) > 3 {
if raw[0] == '\xef' && raw[1] == '\xbb' && raw[2] == '\xbf' {
return raw[3:]
}
}
return raw
}
func RemoveBOMForString(raw string) string {
if len(raw) > 3 {
if raw[0] == '\xef' && raw[1] == '\xbb' && raw[2] == '\xbf' {
return raw[3:]
}
}
return raw
}
func FileLineReader(file string) (chan []byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, errors.Errorf("failed to read file: %s", err)
}
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanLines)
outC := make(chan []byte)
go func() {
defer close(outC)
bomHandled := NewBool(false)
for scanner.Scan() {
raw := bytes.TrimSpace(scanner.Bytes())
if !bomHandled.IsSet() {
raw = RemoveBOM(raw)
bomHandled.Set()
}
outC <- raw
}
}()
return outC, nil
}