go读取配置文件时,经常会出现无法识别文件路径的问题。如果能获取到项目的绝对路径,则可以定位到项目中任意文件位置,那么如何获得项目的绝对路径?

可以使用runtime.Caller()方法获取到执行该方法的“项目文件路径”,然后以此为根据,再定位到其他目录(如根目录)。还有个问题,如在项目中可能有一些相对路径参数,比如配置文件中的相对路径,是根据main运行的地方作为workspace,需要使用os.Chdir()方法切换workspace,这样读取相对路径就没问题了。

confPath := currentAbPath()
RootDir = filepath.Dir(confPath)
os.Chdir(confPath)

currentAbPath方法

(源自:https://zhuanlan.zhihu.com/p/363714760)

// 兼容go run和go build的获取当前执行“文件”路径
func currentAbPath() (dir string) {
	exePath, err := os.Executable()
	if err != nil {
		log.Fatal(err)
	}
	dir, _ = filepath.EvalSymlinks(filepath.Dir(exePath))
	tempDir := os.Getenv("TEMP")
	if tempDir == "" {
		tempDir = os.Getenv("TMP")
	}
	tDir, _ := filepath.EvalSymlinks(tempDir)
	if strings.Contains(dir, tDir)  {
		//return getCurrentAbPathByCaller()
		var abPath string
		_, filename, _, ok := runtime.Caller(0)
		if ok {
			abPath = path.Dir(filename)
		}
		return abPath
	}
	return dir
}

说明:

1.在go run和go build时获取到的路径有所不同,临时目录/项目目录。

2.用其他方法获取路径,一般获取到的都是以调用入口文件的路径,随着主调文件的不同路径也是不一样的,因此无法用来定位绝对路径。而使用上面方法可以永远固定的该代码块出现的文件位置。