fix: strip trailing empty line when reading files

Updated the ReadFile function in 'utilities' by using the Scanner from
the bufio package to read lines from a text file. The trailing empty
line is stripped after scanning and before returning back to the caller.
This commit is contained in:
Dan Anglin 2024-08-15 15:24:25 +01:00
parent eb016b96e9
commit 4e76d20a7a
Signed by: dananglin
GPG key ID: 0C1D44CFBEE68638

View file

@ -1,18 +1,36 @@
package utilities
import (
"bufio"
"errors"
"fmt"
"os"
)
func ReadFile(path string) (string, error) {
data, err := os.ReadFile(path)
file, err := os.Open(path)
if err != nil {
return "", fmt.Errorf("unable to read the data from the file: %w", err)
return "", fmt.Errorf("unable to open %q: %w", path, err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return string(data), nil
if err := scanner.Err(); err != nil {
return "", fmt.Errorf("received an error after scanning the contents from %q: %w", path, err)
}
if lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
return strings.Join(lines, "\n"), nil
}
func FileExists(path string) (bool, error) {