github.com/verrazzano/verrazzano@v1.7.0/tools/psr/backend/osenv/env.go (about)

     1  // Copyright (c) 2022, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package osenv
     5  
     6  import (
     7  	"fmt"
     8  	"os"
     9  )
    10  
    11  type Environment interface {
    12  	LoadFromEnv(cc []EnvVarDesc) error
    13  	GetEnv(string) string
    14  }
    15  
    16  type envData struct {
    17  	envVars map[string]string
    18  }
    19  
    20  var _ Environment = &envData{}
    21  
    22  var GetEnvFunc = os.Getenv
    23  
    24  type EnvVarDesc struct {
    25  	Key        string
    26  	DefaultVal string
    27  	Required   bool
    28  }
    29  
    30  func NewEnv() Environment {
    31  	return &envData{envVars: make(map[string]string)}
    32  }
    33  
    34  // LoadFromEnv get environment vars specified from the EnvVarDesc list and loads them into a map
    35  func (e *envData) LoadFromEnv(cc []EnvVarDesc) error {
    36  	for _, c := range cc {
    37  		if err := e.addItemConfig(c); err != nil {
    38  			return err
    39  		}
    40  	}
    41  	return nil
    42  }
    43  
    44  // GetEnv returns a value for a specific key
    45  func (e *envData) GetEnv(key string) string {
    46  	return e.envVars[key]
    47  }
    48  
    49  // addItemToConfig gets the env var item and loads it into a map.
    50  // If the env var is missing and required then return an error
    51  // If the env var is missing and not required then return the default
    52  func (e *envData) addItemConfig(c EnvVarDesc) error {
    53  	val := GetEnvFunc(c.Key)
    54  	if len(val) == 0 {
    55  		if c.Required {
    56  			return fmt.Errorf("Failed, missing required Env var %s", c.Key)
    57  		}
    58  		val = c.DefaultVal
    59  	}
    60  	e.envVars[c.Key] = val
    61  	return nil
    62  }