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"