Skip to content

Instantly share code, notes, and snippets.

@moonsub-kim
Created January 6, 2021 08:55
Show Gist options
  • Save moonsub-kim/55d15c47963bf34e7d6d9689fe4ec90e to your computer and use it in GitHub Desktop.
Save moonsub-kim/55d15c47963bf34e7d6d9689fe4ec90e to your computer and use it in GitHub Desktop.
Read env vars using viper
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