viper cannot be used in init function, Right? #1279
-
Here is my codevar (
Rdb *redis.Client
Ctx context.Context
)
func init() {
fmt.Println("Start to init conn package >>>>>>>>> ")
redisUrl := viper.Get("datasource.redis.url").(string)
fmt.Println("Failed to parse configuration file")
Rdb = db.RedisClient(redisUrl)
Ctx = context.Background()
} Error messageIt doesn't print "Failed to parse ...."
|
Beta Was this translation helpful? Give feedback.
Answered by
sagikazarmark
Jan 7, 2022
Replies: 1 comment 1 reply
-
Well, there is nothing that keeps you from using it in an init function, but if there is nothing available under a certain key, it will return nil. Viper doesn't load files automatically. See the readme for examples. Technically, the offending line is this: You could change it to make the error go away, but it would still not return anything: |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
pplmx
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well, there is nothing that keeps you from using it in an init function, but if there is nothing available under a certain key, it will return nil.
Viper doesn't load files automatically. See the readme for examples.
Technically, the offending line is this:
redisUrl := viper.Get("datasource.redis.url").(string)
You could change it to make the error go away, but it would still not return anything:
redisUrl, ok := viper.Get("datasource.redis.url").(string)