go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/fileutil/read_lines.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package fileutil
     9  
    10  import (
    11  	"bufio"
    12  	"os"
    13  )
    14  
    15  // ReadLines reads a file and calls the handler for each line.
    16  func ReadLines(filePath string, handler func(string) error) error {
    17  	f, err := os.Open(filePath)
    18  	if err != nil {
    19  		return err
    20  	}
    21  	defer func() { _ = f.Close() }()
    22  
    23  	scanner := bufio.NewScanner(f)
    24  	for scanner.Scan() {
    25  		line := scanner.Text()
    26  		err = handler(line)
    27  		if err != nil {
    28  			return err
    29  		}
    30  	}
    31  	return nil
    32  }