From 6e2c9e7cd4fbf263348847213b9d55eae3c0139f Mon Sep 17 00:00:00 2001 From: Asim Aslam Date: Fri, 25 Sep 2020 10:24:02 +0100 Subject: [PATCH] env config implementation (#2024) --- config/env/env.go | 48 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 config/env/env.go diff --git a/config/env/env.go b/config/env/env.go new file mode 100644 index 00000000..d60a61a1 --- /dev/null +++ b/config/env/env.go @@ -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) +}