package config import ( "errors" "fmt" "log/slog" "os" "strings" ) const ( CardmarketAppToken = "CM_APP_TOKEN" CardmarketAppSecret = "CM_APP_SECRET" CardmarketAccessToken = "CM_ACCESS_TOKEN" CardmarketAccessTokenSecret = "CM_ACCESS_TOKEN_SECRET" CardmarketApiBaseURL = "CM_API_BASE_URL" AppLogLevel = "APP_LOG_LEVEL" ) var ( ErrMissingCardmarketAppToken = errors.New("err: missing " + CardmarketAppToken + " in ENV") ErrMissingCardmarketAppSecret = errors.New("err: missing " + CardmarketAppSecret + " in ENV") ErrMissingCardmarketAccessToken = errors.New("err: missing " + CardmarketAccessToken + " in ENV") ErrMissingCardmarketAccessTokenSecret = errors.New("err: missing " + CardmarketAccessTokenSecret + " in ENV") ErrMissingCardmarketApiBaseURL = errors.New("err: missing " + CardmarketApiBaseURL + " in ENV") ) type CardmarketApiAuth struct { AppToken []byte AppSecret []byte AccessToken []byte AccessTokenSecret []byte } func (auth *CardmarketApiAuth) String() string { return fmt.Sprintf( "CardmarketApiAuth{AppToken: %s, AppSecret: %s, AccessToken: %s, AccessTokenSecret: %s}", string(auth.AppToken[:3])+strings.Repeat("*", 5), string(auth.AppSecret[:3])+strings.Repeat("*", 5), string(auth.AccessToken[:3])+strings.Repeat("*", 5), string(auth.AccessTokenSecret[:3])+strings.Repeat("*", 5), ) } type Config struct { CardmarketApiBaseURL []byte CardmarketApiAuth CardmarketApiAuth AppLogLevel slog.Level } func NewConfigFromEnv() (Config, error) { appToken := os.Getenv(CardmarketAppToken) if appToken == "" { return Config{}, ErrMissingCardmarketAppToken } appSecret := os.Getenv(CardmarketAppSecret) if appSecret == "" { return Config{}, ErrMissingCardmarketAppSecret } accessToken := os.Getenv(CardmarketAccessToken) if accessToken == "" { return Config{}, ErrMissingCardmarketAccessToken } accessTokenSecret := os.Getenv(CardmarketAccessTokenSecret) if accessTokenSecret == "" { return Config{}, ErrMissingCardmarketAccessTokenSecret } apiBaseURL := os.Getenv(CardmarketApiBaseURL) if apiBaseURL == "" { return Config{}, ErrMissingCardmarketApiBaseURL } lvl := slog.LevelDebug appLogLevel := os.Getenv(AppLogLevel) if lvlErr := lvl.UnmarshalText([]byte(appLogLevel)); lvlErr != nil { return Config{}, errors.Join(errors.New("could not unmarshal "+AppLogLevel), lvlErr) } return Config{ CardmarketApiBaseURL: []byte(apiBaseURL), CardmarketApiAuth: CardmarketApiAuth{ AppToken: []byte(appToken), AppSecret: []byte(appSecret), AccessToken: []byte(accessToken), AccessTokenSecret: []byte(accessTokenSecret), }, AppLogLevel: lvl, }, nil } func (conf *Config) String() string { return fmt.Sprintf( "Config{CardmarketApiBaseURL: %s, CardmarketApiAuth: %s, AppLogLevel: %s}", conf.CardmarketApiBaseURL, conf.CardmarketApiAuth.String(), conf.AppLogLevel, ) }