env config implementation (#2024)

This commit is contained in:
Asim Aslam
2020-09-25 10:24:02 +01:00
committed by GitHub
parent 4028e0156b
commit 6e2c9e7cd4

48
config/env/env.go vendored Normal file
View File

@@ -0,0 +1,48 @@
// Package env provides config from environment variables
package env
import (
"encoding/json"
"os"
"strings"
"github.com/micro/go-micro/v3/config"
)
type envConfig struct{}
// NewConfig returns new config
func NewConfig() (*envConfig, error) {
return new(envConfig), nil
}
func formatKey(v string) string {
if len(v) == 0 {
return ""
}
v = strings.ToUpper(v)
return strings.Replace(v, ".", "_", -1)
}
func (c *envConfig) Get(path string, options ...config.Option) (config.Value, error) {
v := os.Getenv(formatKey(path))
if len(v) == 0 {
v = "{}"
}
return config.NewJSONValue([]byte(v)), nil
}
func (c *envConfig) Set(path string, val interface{}, options ...config.Option) error {
key := formatKey(path)
v, err := json.Marshal(val)
if err != nil {
return err
}
return os.Setenv(key, string(v))
}
func (c *envConfig) Delete(path string, options ...config.Option) error {
v := formatKey(path)
return os.Unsetenv(v)
}