Created
January 6, 2021 08:55
-
-
Save moonsub-kim/55d15c47963bf34e7d6d9689fe4ec90e to your computer and use it in GitHub Desktop.
Read env vars using viper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/mitchellh/mapstructure" | |
"github.com/spf13/viper" | |
) | |
type Config struct { | |
MysqlHost string `mapstructure:"MYSQL_HOST"` | |
LogLevel string `mapstructure:"LOG_LEVEL"` | |
SentryDSN string `mapstructure:"SENTRY_DSN"` | |
} | |
func (c *Config) keys() ([]string, error) { | |
m := &map[string]interface{}{} | |
err := mapstructure.Decode(c, &m) | |
if err != nil { | |
return nil, err | |
} | |
var keys []string | |
for k := range *m { | |
keys = append(keys, k) | |
} | |
return keys, nil | |
} | |
func (c *Config) BindEnv() error { | |
keys, err := c.keys() | |
if err != nil { | |
return err | |
} | |
v := viper.New() | |
for _, k := range keys { | |
err = v.BindEnv(k) | |
if err != nil { // env 를 optional로 쓰기 힘들듯함 | |
return err | |
} | |
} | |
err = v.Unmarshal(&c) | |
if err != nil { | |
return err | |
} | |
return nil | |
} | |
func NewConfig() (*Config, error) { | |
c := &Config{} | |
err := c.BindEnv() | |
if err != nil { | |
return nil, err | |
} | |
return c, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment