github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/config/env/env.go (about)

     1  // Licensed under the Apache License, Version 2.0 (the "License");
     2  // you may not use this file except in compliance with the License.
     3  // You may obtain a copy of the License at
     4  //
     5  //     https://www.apache.org/licenses/LICENSE-2.0
     6  //
     7  // Unless required by applicable law or agreed to in writing, software
     8  // distributed under the License is distributed on an "AS IS" BASIS,
     9  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    10  // See the License for the specific language governing permissions and
    11  // limitations under the License.
    12  //
    13  // Original source: github.com/micro/go-micro/v3/config/env/env.go
    14  
    15  // Package env provides config from environment variables
    16  package env
    17  
    18  import (
    19  	"encoding/json"
    20  	"os"
    21  	"strings"
    22  
    23  	"github.com/tickoalcantara12/micro/v3/service/config"
    24  )
    25  
    26  type envConfig struct{}
    27  
    28  // NewConfig returns new config
    29  func NewConfig() (*envConfig, error) {
    30  	return new(envConfig), nil
    31  }
    32  
    33  func formatKey(v string) string {
    34  	if len(v) == 0 {
    35  		return ""
    36  	}
    37  
    38  	v = strings.ToUpper(v)
    39  	return strings.Replace(v, ".", "_", -1)
    40  }
    41  
    42  func (c *envConfig) Get(path string, options ...config.Option) (config.Value, error) {
    43  	v := os.Getenv(formatKey(path))
    44  	if len(v) == 0 {
    45  		v = "{}"
    46  	}
    47  	return config.NewJSONValue([]byte(v)), nil
    48  }
    49  
    50  func (c *envConfig) Set(path string, val interface{}, options ...config.Option) error {
    51  	key := formatKey(path)
    52  	v, err := json.Marshal(val)
    53  	if err != nil {
    54  		return err
    55  	}
    56  	return os.Setenv(key, string(v))
    57  }
    58  
    59  func (c *envConfig) Delete(path string, options ...config.Option) error {
    60  	v := formatKey(path)
    61  	return os.Unsetenv(v)
    62  }