如何覆盖配置?

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

How to override configuration?

问题

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

configs/.dev.env

deploy_env=dev

configs/.env

deploy_env=local

main.go

package main

import (
	"fmt"
	"os"

	"github.com/joho/godotenv"
)

func main() {
	err := godotenv.Load("./configs/.env") // 加载
	if err != nil {
		fmt.Println("无法加载")
	}
	err = godotenv.Load("./configs/.dev.env") // 期望覆盖配置
	if err != nil {
		fmt.Println("无法加载")
	}
	fmt.Println(os.Getenv("deploy_env")) // 输出为:local
                                       // 期望输出:dev
}

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

英文:

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

configs/.dev.env

  deploy_env=dev

configs/.env

  deploy_env=local

main.go

package main

import (
	"fmt"
	"os"

	"github.com/joho/godotenv"
)

func main() {
	err := godotenv.Load("./configs/.env") // load
	if err != nil {
		fmt.Println("unable to load")
	}
	err = godotenv.Load("./configs/.dev.env") // expecting to override configuration
	if err != nil {
		fmt.Println("unable to load")
	}
	fmt.Println(os.Getenv("deploy_env")) // Got output as: local       
                                         // Expecting output: dev
}

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:

确定