viper-app/pkg/file/file.go

42 lines
750 B
Go

package file
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
}
func Size(path string) (int64, error) {
info, err := os.Stat(path)
if err != nil {
return 0, err
}
return info.Size(), err
}