doupingmao1903 2018-10-03 13:37
浏览 267
已采纳

使用IntelliJ运行Go应用程序时加载配置文件

I use MacOS Mojave with IntelliJ Ultimate 2018.2.

I wrote a go application that loads a config file from the directory of my project. I created an InitConfig() function to load the JSON file into a struct. this is thee code of my Config.go file

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)
    }
}

I use a variable called ExPath that contains the current directory of the running binary, I created it with the following code (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)
}

when I try to run or debug the application, intellij is creating a directory where it compiles and runs the application, how can I tell it to also copy the json file?

when I try to run/debug my App I get:

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

I checked and that directory really doesn't contain my config directory. so.. is there a way to let intellij know it should copy it before executing my project?

thanks!

  • 写回答

1条回答 默认 最新

  • dpglo66848 2018-10-03 14:22
    关注

    it seems that the solution is simple. all I needed is to set the "Output Directory" of my run/debug configuration to my project's directory. and then intellij executes the file in that same directory and it can find /config/config.json.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条