go获得项目根目录

01 使用 os.Getwd

Go 语言标准库 os 中有一个函数 Getwd

func Getwd() (dir string, err error)

它返回当前工作目录。

基于此,我们可以得到项目根目录。还是上面的目录结构,切换到 /Users/xuxinhua/stdcwd,然后执行程序:

$ cd /Users/xuxinhua/stdcwd
$ bin/cwd

这时,当前目录(os.Getwd 的返回值)就是 /Users/xuxinhua/stdcwd

但是,如果我们不在这个目录执行的 bin/cwd,当前目录就变了。因此,这不是一种好的方式。

不过,我们可以要求必须在 /Users/xuxinhua/stdcwd 目录运行程序,否则报错,具体怎么做到限制,留给你思考。

02 使用 exec.LookPath

在上面的目录结构中,如果我们能够获得程序 cwd 所在目录,也就相当于获得了项目根目录。

binary, err := exec.LookPath(os.Args[0])

os.Args[0] 是当前程序名。如果我们在项目根目录执行程序 bin/cwd,以上程序返回的 binary 结果是 bin/cwd,即程序 cwd 的相对路径,可以通过 filepath.Abs() 函数得到绝对路径,最后通过调用两次 filepath.Dir 得到项目根目录。

binary, _ := exec.LookPath(os.Args[0])
root := filepath.Dir(filepath.Dir(filepath.Abs(binary)))

03 使用 os.Executable

可能是类似的需求很常见,Go 在 1.8 专门为这样的需求增加了一个函数:

// Executable returns the path name for the executable that started the current process.
// There is no guarantee that the path is still pointing to the correct executable.
// If a symlink was used to start the process, depending on the operating system, the result might be the symlink or the path it pointed to.
// If a stable result is needed, path/filepath.EvalSymlinks might help.
// Executable returns an absolute path unless an error occurred.
// The main use case is finding resources located relative to an executable.
func Executable() (string, error)

和 exec.LookPath 类似,不过该函数返回的结果是绝对路径。因此,不需要经过 filepath.Abs 处理。

binary, _ := os.Executable()
root := filepath.Dir(filepath.Dir(binary))

注意,exec.LookPath 和 os.Executable 的结果都是可执行程序的路径,包括可执行程序本身,比如 /Users/xuxinhua/stdcwd/bin/cwd

细心的读者可能会注意到该函数注释中提到符号链接问题,为了获得稳定的结果,我们应该借助 filepath.EvalSymlinks 进行处理。

package main

import (
    "fmt"
    "os"
    "path/filepath"
posted @ 2021-11-02 19:42  技术颜良  阅读(1835)  评论(0编辑  收藏  举报