如何打开一个位于与主文件不同文件夹中的配置文件?

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

How do I open a config file that is located in a folder not with the main file?

问题

我想给我的项目添加一个配置,并且我有这样的项目结构:

app:
  -cmd
    - main
       -app.go
  -internal
    - config
        -config.go
  -pkg
  config.yaml
  go.mod
  go.sum

在配置文件中,我想读取config.yaml:

func GetConfig() *Config {
	once.Do(func() {
		instance = &Config{}
		logger := logging.GetLogger("info")
		logger.Info("start config initialisation")
		if err := cleanenv.ReadConfig("config.yaml", instance); err != nil {
			help, _ := cleanenv.GetDescription(instance, nil)
			logger.Info(help)
			logger.Fatal(err)
		}

	})
	return instance
}

然后我得到一个错误:系统找不到指定的文件
为了修复它,我需要将配置文件移动到应用程序启动的文件夹中,也就是cmd/main
我想知道是否有可能通过某种方式修复它,使得文件与项目的初始化一起放置,与go.mod等文件放在一起。我尝试在读取文件的位置指定不同的路径,但是没有成功。

我使用cleanenv库进行读取

英文:

I want to add a configuration to my project and i have such a project structure:

app:
  -cmd
    - main
       -app.go
  -internal
    - config
        -config.go
  -pkg
  config.yaml
  go.mod
  go.sum

In the config file, I want to read config.yaml:

func GetConfig() *Config {
	once.Do(func() {
		instance = &Config{}
		logger := logging.GetLogger("info")
		logger.Info("start config initialisation")
		if err := cleanenv.ReadConfig("config.yaml", instance); err != nil {
			help, _ := cleanenv.GetDescription(instance, nil)
			logger.Info(help)
			logger.Fatal(err)
		}

	})
	return instance
}

And I get an error: system cannot find the file specified.
And to fix it, I need to move the configuration file to the folder where the application is launched, that is, to cmd/main
And I wonder if it is possible to fix it somehow so that the file lies together with the initialization of the project along with go.mod and so on.I tried to specify different paths in the place of reading the file, but nothing worked.

I use the cleanenv library for reading

答案1

得分: 2

wd,err := os.Getwd()
if err != nil {
    // 处理错误
}
parentTop := filepath.Dir(wd) // 如果你的工作目录是顶级目录,可以跳过这一步
// 使用 parent 和 `parentTop + "/pkg/config.yaml"`

然后使用 parent 和 parentTop + "/pkg/config.yaml"

英文:
wd,err := os.Getwd()
if err != nil {
    // handle error
}
parentTop := filepath.Dir(wd) // if your working directory is top level you can skip this step
// and wd instead

then use the parent and parentTop +"/pkg/config.yaml"

huangapple
  • 本文由 发表于 2022年7月20日 22:35:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/73053582.html
匿名

发表评论

匿名网友

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

确定