github.com/Axway/agent-sdk@v1.1.101/pkg/util/envfile.go (about)

     1  package util
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"io"
     7  	"os"
     8  	"strings"
     9  
    10  	"github.com/subosito/gotenv"
    11  )
    12  
    13  // LoadEnvFromFile - Loads the environment variables from a file
    14  func LoadEnvFromFile(filename string) error {
    15  	if filename != "" {
    16  		// have to do filtering before using the gotenv library. While the library trims trailing
    17  		// whitespace, a TAB char is no considered whitespace and isn't trimmed. Otherwise, we
    18  		// just could have called gotenv.Load and skipped all of this.
    19  		f, err := os.Open(filename)
    20  		if err != nil {
    21  			return err
    22  		}
    23  
    24  		defer f.Close()
    25  
    26  		buf := filterLines(f)
    27  		r := bytes.NewReader(buf.Bytes())
    28  
    29  		return gotenv.Apply(r)
    30  	}
    31  
    32  	return nil
    33  }
    34  
    35  func filterLines(r io.Reader) bytes.Buffer {
    36  	var lf = []byte("\n")
    37  
    38  	var out bytes.Buffer
    39  	scanner := bufio.NewScanner(r)
    40  
    41  	for scanner.Scan() {
    42  		line := scanner.Text()
    43  
    44  		// trim out trailing spaces AND tab chars
    45  		trimmedLine := strings.TrimRight(line, " \t")
    46  		out.Write([]byte(trimmedLine))
    47  		out.Write(lf)
    48  	}
    49  
    50  	return out
    51  }