遇到的问题
open ./config/my.ini: no such file or directory
报错代码如下:
conf, err := ini.Load("./config/my.ini")
if err != nil {
log.Fatal("配置文件读取失败, err = ", err)
}
我们通过分析以及查询资料得知,Golang的相对路径是相对于执行命令时的目录;自然也就读取不到了
剖析问题
go run
go help run
Run compiles and runs the main package comprising the named Go source files.
A Go source file is defined to be a file ending in a literal ".go" suffix.
go run/tmp/go-build...
go run main.go/tmp/go-build962610262/b001/exe
这就已经很清楚了,那么我们想想,会出现哪些问题呢
- 依赖相对路径的文件,出现路径出错的问题
- go run 和 go build 不一样,一个到临时目录下执行,一个可手动在编译后的目录下执行,路径的处理方式会不同
- 不断go run,不断产生新的临时文件
这其实就是根本原因了,因为 go run 和 go build 的编译文件执行路径并不同,执行的层级也有可能不一样,自然而然就出现各种读取不到的奇怪问题了
解决方案
GetAppPath()go build main.go./src/gin-blog/main
import (
"path/filepath"
"os"
"os/exec"
"string"
)
func GetAppPath() string {
file, _ := exec.LookPath(os.Args[0])
path, _ := filepath.Abs(file)
index := strings.LastIndex(path, string(os.PathSeparator))
return path[:index]
}
go run
go run
package main
import (
"flag"
"fmt"
)
func main() {
var appPath string
flag.StringVar(&appPath, "app-path", "app-path")
flag.Parse()
fmt.Printf("App path: %s", appPath)
}
运行
go run main.go --app-path "Your project address"
最终代码
file, _ := exec.LookPath(os.Args[0])
path, _ := filepath.Abs(file)
index := strings.LastIndex(path, string(os.PathSeparator))
path = path[:index]
conf, err := ini.Load(path + "/config/my.ini")
if err != nil {
log.Fatal("配置文件读取失败, err = ", err)
}