This commit is contained in:
Will Charczuk 2017-04-25 20:01:48 -07:00
parent fc75f205ee
commit da432bc1db
2 changed files with 37 additions and 18 deletions

View File

@ -14,24 +14,30 @@ var (
type fileUtil struct{}
// ReadByLines reads a file and calls the handler for each line.
func (fu fileUtil) ReadByLines(filePath string, handler func(line string)) error {
if f, err := os.Open(filePath); err == nil {
func (fu fileUtil) ReadByLines(filePath string, handler func(line string) error) error {
var f *os.File
var err error
if f, err = os.Open(filePath); err == nil {
defer f.Close()
var line string
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
handler(line)
line = scanner.Text()
err = handler(line)
if err != nil {
return err
}
}
} else {
return err
}
return nil
return err
}
// ReadByChunks reads a file in `chunkSize` pieces, dispatched to the handler.
func (fu fileUtil) ReadByChunks(filePath string, chunkSize int, handler func(line []byte)) error {
if f, err := os.Open(filePath); err == nil {
func (fu fileUtil) ReadByChunks(filePath string, chunkSize int, handler func(line []byte) error) error {
var f *os.File
var err error
if f, err = os.Open(filePath); err == nil {
defer f.Close()
chunk := make([]byte, chunkSize)
@ -41,10 +47,11 @@ func (fu fileUtil) ReadByChunks(filePath string, chunkSize int, handler func(lin
break
}
readData := chunk[:readBytes]
handler(readData)
err = handler(readData)
if err != nil {
return err
}
}
} else {
return err
}
return nil
return err
}

View File

@ -10,21 +10,33 @@ type ValueFormatter func(v interface{}) string
// TimeValueFormatter is a ValueFormatter for timestamps.
func TimeValueFormatter(v interface{}) string {
return TimeValueFormatterWithFormat(v, DefaultDateFormat)
return formatTime(v, DefaultDateFormat)
}
// TimeHourValueFormatter is a ValueFormatter for timestamps.
func TimeHourValueFormatter(v interface{}) string {
return TimeValueFormatterWithFormat(v, DefaultDateHourFormat)
return formatTime(v, DefaultDateHourFormat)
}
// TimeMinuteValueFormatter is a ValueFormatter for timestamps.
func TimeMinuteValueFormatter(v interface{}) string {
return TimeValueFormatterWithFormat(v, DefaultDateMinuteFormat)
return formatTime(v, DefaultDateMinuteFormat)
}
// TimeDateValueFormatter is a ValueFormatter for timestamps.
func TimeDateValueFormatter(v interface{}) string {
return formatTime(v, "2006-01-02")
}
// TimeValueFormatterWithFormat returns a time formatter with a given format.
func TimeValueFormatterWithFormat(format string) ValueFormatter {
return func(v interface{}) string {
return formatTime(v, format)
}
}
// TimeValueFormatterWithFormat is a ValueFormatter for timestamps with a given format.
func TimeValueFormatterWithFormat(v interface{}, dateFormat string) string {
func formatTime(v interface{}, dateFormat string) string {
if typed, isTyped := v.(time.Time); isTyped {
return typed.Format(dateFormat)
}