如何覆盖配置?

huangapple go评论114阅读模式
英文:

How to override configuration?

问题

我们有针对每个部署环境的配置文件,如下所示:

configs/.dev.env

  1. deploy_env=dev

configs/.env

  1. deploy_env=local

main.go

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/joho/godotenv"
  6. )
  7. func main() {
  8. err := godotenv.Load("./configs/.env") // 加载
  9. if err != nil {
  10. fmt.Println("无法加载")
  11. }
  12. err = godotenv.Load("./configs/.dev.env") // 期望覆盖配置
  13. if err != nil {
  14. fmt.Println("无法加载")
  15. }
  16. fmt.Println(os.Getenv("deploy_env")) // 输出为:local
  17. // 期望输出:dev
  18. }

如何覆盖配置?期望将 deploy_env 设置为 dev

英文:

We have configuration file per deploy environment, as shown in below code:

configs/.dev.env

  1. deploy_env=dev

configs/.env

  1. deploy_env=local

main.go

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/joho/godotenv"
  6. )
  7. func main() {
  8. err := godotenv.Load("./configs/.env") // load
  9. if err != nil {
  10. fmt.Println("unable to load")
  11. }
  12. err = godotenv.Load("./configs/.dev.env") // expecting to override configuration
  13. if err != nil {
  14. fmt.Println("unable to load")
  15. }
  16. fmt.Println(os.Getenv("deploy_env")) // Got output as: local
  17. // Expecting output: dev
  18. }

How to override configuration? expecting deploy_env to set as dev?

答案1

得分: 2

使用Overload代替Load

源代码

英文:

Use Overload instead of Load

source

huangapple
  • 本文由 发表于 2022年8月16日 21:14:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/73374612.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定