代码之家  ›  专栏  ›  技术社区  ›  ufk

使用intellij运行go应用程序时加载配置文件

  •  0
  • ufk  · 技术社区  · 6 年前

    我使用Macos Mojave和Intellij Ultimate 2018.2。

    我编写了一个从我的项目目录中加载配置文件的Go应用程序。我创造了一个 InitConfig() 函数将JSON文件加载到结构中。这是我的密码 Config.go 文件

    package main
    
    import (
        "github.com/tkanos/gonfig"
        "log"
    )
    
    type Configuration struct {
        WebServerPort   int
        DbName string
        DbUser string
        DbPassword string
        DbPort int
        CertFile string
        KeyFile string
        EnableHttps bool
    }
    
    var AppConfiguration Configuration
    
    func InitConfig() {
        AppConfiguration = Configuration{}
        err := gonfig.GetConf(ExPath + "/config/config.json", &AppConfiguration)
        if err != nil {
            log.Fatalf("could not parse configuration file: %v",err)
        }
    }
    

    我使用一个名为 ExPath 它包含正在运行的二进制文件的当前目录,我用以下代码(path.go)创建了它:

    package main
    
    import (
        "log"
        "os"
        "path/filepath"
    )
    
    var ExPath string
    
    func InitPath() {
        ex, err := os.Executable()
        if err != nil {
            log.Fatalf("could not get executable path: %v",err)
        }
        ExPath = filepath.Dir(ex)
    }
    

    当我尝试运行或调试应用程序时,Intellij正在创建一个目录,它在其中编译和运行应用程序,我如何告诉它也复制JSON文件?

    当我尝试运行/调试我的应用程序时,我得到:

    could not parse configuration file: open /private/var/folders/60/qzt2pgs173s4j_r6lby_mw1c0000gn/T/config/config.json: no such file or directory
    

    我查过了,那个目录真的不包含我的配置目录。所以…有没有办法让intellij知道在执行我的项目之前应该复制它?

    谢谢!

    1 回复  |  直到 6 年前
        1
  •  0
  •   ufk    6 年前

    解决方案似乎很简单。我所需要的只是将我的运行/调试配置的“输出目录”设置为我的项目目录。然后Intellij执行同一目录中的文件,它可以找到 /config/config.json .