github.com/seeker-insurance/kit@v0.0.13/env/env.go (about)

     1  //Package env contains helper functions for setting and getting environment variables
     2  package env
     3  
     4  import (
     5  	"fmt"
     6  	"log"
     7  	"os"
     8  	"strconv"
     9  	"strings"
    10  
    11  	"github.com/spf13/viper"
    12  )
    13  
    14  //Key is the key string of an environment variable.
    15  type Key string
    16  
    17  //Value is an alias for os.GetEnv(string(key))
    18  func (key Key) Value() string {
    19  	return os.Getenv(string(key))
    20  }
    21  
    22  //Lookup is an alias for os.LookupEnv(string(key))
    23  func (key Key) Lookup() (string, bool) {
    24  	return os.LookupEnv(string(key))
    25  }
    26  
    27  //SetString sets the string address pointed to by sp to key.Value().
    28  func (key Key) SetString(sp *string) error {
    29  	val, ok := key.Lookup()
    30  	if !ok {
    31  		return fmt.Errorf("missing environment variable %s", key)
    32  	}
    33  	*sp = val
    34  	return nil
    35  }
    36  
    37  //SetInt sets the int address pointed to by ip to key.Value().
    38  func (key Key) SetInt(ip *int) error {
    39  	val, ok := key.Lookup()
    40  	if !ok {
    41  		return fmt.Errorf("env.Key.SetInt: missing environment variable %s", key)
    42  	}
    43  	asInt, err := strconv.Atoi(val)
    44  	if err != nil {
    45  		return fmt.Errorf("env.Key.SetInt: strconv.Atoi: %v", err)
    46  	}
    47  	*ip = asInt
    48  	return nil
    49  }
    50  
    51  //SetBool sets the boolean address pointed to by bp to key.Value()
    52  func (key Key) SetBool(bp *bool) error {
    53  	str := string(key)
    54  	val, ok := os.LookupEnv(str)
    55  	if !ok {
    56  		return fmt.Errorf("env.Key.SetBool: missing environment variable %s", key)
    57  	}
    58  	asBool, err := strconv.ParseBool(val)
    59  	if err != nil {
    60  		return fmt.Errorf("env.Key.SetInt: strconv.ParseBool: %v", err)
    61  	}
    62  	*bp = asBool
    63  	return nil
    64  }
    65  
    66  //Check checks the local environment to see that all of the environment variables specified in config are set.
    67  func Check() {
    68  	var missing []string
    69  	for _, key := range viper.GetStringSlice("env_var_names") {
    70  		if _, ok := os.LookupEnv(key); !ok {
    71  			missing = append(missing, key)
    72  		}
    73  	}
    74  	if len(missing) > 0 {
    75  		log.Fatalf("CheckEnv(): missing the following environmental variables: \n\t%s", strings.Join(missing, "\n\t"))
    76  	}
    77  }