viper-app/pkg/file.go
2023-02-03 16:18:31 +08:00

34 lines
617 B
Go

package pkg
import (
"bufio"
"go.uber.org/zap"
"os"
)
func ScanFile(path string, handle func(data string) (err error)) (err error) {
file, err := os.Open(path)
if err != nil {
return err
}
defer func(file *os.File) {
err = file.Close()
if err != nil {
zap.S().Error(err)
}
}(file)
input := bufio.NewScanner(file)
var lineText string
for input.Scan() {
lineText = input.Text()
err := handle(lineText)
if err != nil && len(lineText) > 0 {
zap.L().Error("file data handle error", zap.Error(err), zap.String("path", path), zap.String("data", lineText))
continue
}
}
return nil
}