github.com/PDOK/gokoala@v0.50.6/internal/engine/util/filereader.go (about)

     1  package util
     2  
     3  import (
     4  	"bytes"
     5  	"compress/gzip"
     6  	"errors"
     7  	"io"
     8  	"io/fs"
     9  	"log"
    10  	"os"
    11  )
    12  
    13  // ReadFile read a plain or gzipped file and return contents as string
    14  func ReadFile(filePath string) string {
    15  	gzipFile := filePath + ".gz"
    16  	var fileContents string
    17  	if _, err := os.Stat(gzipFile); !errors.Is(err, fs.ErrNotExist) {
    18  		fileContents, err = readGzipContents(gzipFile)
    19  		if err != nil {
    20  			log.Fatalf("unable to decompress gzip file %s", gzipFile)
    21  		}
    22  	} else {
    23  		fileContents, err = readPlainContents(filePath)
    24  		if err != nil {
    25  			log.Fatalf("unable to read file %s", filePath)
    26  		}
    27  	}
    28  	return fileContents
    29  }
    30  
    31  // decompress gzip files, return contents as string
    32  func readGzipContents(filePath string) (string, error) {
    33  	gzipFile, err := os.Open(filePath)
    34  	if err != nil {
    35  		return "", err
    36  	}
    37  	defer func(gzipFile *os.File) {
    38  		err := gzipFile.Close()
    39  		if err != nil {
    40  			log.Println("failed to close gzip file")
    41  		}
    42  	}(gzipFile)
    43  	gzipReader, err := gzip.NewReader(gzipFile)
    44  	if err != nil {
    45  		return "", err
    46  	}
    47  	defer func(gzipReader *gzip.Reader) {
    48  		err := gzipReader.Close()
    49  		if err != nil {
    50  			log.Println("failed to close gzip reader")
    51  		}
    52  	}(gzipReader)
    53  	var buffer bytes.Buffer
    54  	_, err = io.Copy(&buffer, gzipReader) //nolint:gosec
    55  	if err != nil {
    56  		return "", err
    57  	}
    58  	return buffer.String(), nil
    59  }
    60  
    61  // read file, return contents as string
    62  func readPlainContents(filePath string) (string, error) {
    63  	file, err := os.Open(filePath)
    64  	if err != nil {
    65  		return "", err
    66  	}
    67  	defer func(file *os.File) {
    68  		err := file.Close()
    69  		if err != nil {
    70  			log.Println("failed to close file")
    71  		}
    72  	}(file)
    73  	var buffer bytes.Buffer
    74  	_, err = io.Copy(&buffer, file)
    75  	if err != nil {
    76  		return "", err
    77  	}
    78  	return buffer.String(), nil
    79  }