github.com/pavlo67/common@v0.5.3/common/config/envs.go (about)

     1  package config
     2  
     3  import (
     4  	"io/ioutil"
     5  
     6  	"github.com/pavlo67/common/common/serialization"
     7  
     8  	"github.com/pavlo67/common/common"
     9  	"github.com/pavlo67/common/common/errors"
    10  )
    11  
    12  type Envs struct {
    13  	Data      common.Map
    14  	Marshaler serialization.Marshaler
    15  }
    16  
    17  var errNoEnvs = errors.New("no envs")
    18  
    19  func (c *Envs) Raw(key string) (interface{}, error) {
    20  	if c == nil {
    21  		return nil, errNoEnvs
    22  	}
    23  
    24  	valueRaw, ok := c.Data[key]
    25  	if !ok {
    26  		return nil, errors.CommonError(common.NotFoundKey, common.Map{"reason": "no key in envs", "key": key})
    27  	}
    28  
    29  	return valueRaw, nil
    30  }
    31  
    32  func (c *Envs) Value(key string, target interface{}) error {
    33  	if c == nil {
    34  		return errNoEnvs
    35  	}
    36  
    37  	if value, ok := c.Data[key]; ok {
    38  		valueRaw, err := c.Marshaler.Marshal(value)
    39  		if err != nil {
    40  			return errors.Wrapf(err, "can't marshal value (%s / %#v) to raw bytes", key, value)
    41  		}
    42  
    43  		return c.Marshaler.Unmarshal(valueRaw, target)
    44  	}
    45  
    46  	return errors.CommonError(common.NotFoundKey, common.Map{"reason": "no key in envs", "key": key})
    47  }
    48  
    49  // -----------------------------------------------------------------------------
    50  
    51  func Get(envsFile string, marshaler serialization.Marshaler) (*Envs, error) {
    52  
    53  	if len(envsFile) < 1 {
    54  		return nil, errors.New("empty envs path")
    55  	}
    56  
    57  	dataBytes, err := ioutil.ReadFile(envsFile)
    58  	if err != nil {
    59  		return nil, errors.Wrapf(err, "can't read envs file from '%s'", envsFile)
    60  	}
    61  
    62  	envs := Envs{Marshaler: marshaler}
    63  
    64  	if err = marshaler.Unmarshal(dataBytes, &envs.Data); err != nil {
    65  		return nil, errors.Wrapf(err, "can't .Unmarshal('%s') from envs '%s'", dataBytes, envsFile)
    66  	}
    67  
    68  	return &envs, nil
    69  }