Golang 擷取使用者 home 目錄路徑

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

os/user

一般情況下我們可以使用 os/user 包提供的 Current() 函數來擷取使用者資訊:

user, err := user.Current()if nil == err {return user.HomeDir, nil}

但這個方式交叉編譯後不能完全跨平台,在 darwin 下需要 cgo 才能正常工作。

改進

為瞭解決這個問題,我們需要進行一點增強,在通過 os/user 擷取失敗時再通過環境變數、命令來擷取:

// Home returns the home directory for the executing user.//// This uses an OS-specific method for discovering the home directory.// An error is returned if a home directory cannot be detected.func Home() (string, error) {user, err := user.Current()if nil == err {return user.HomeDir, nil}// cross compile support    if "windows" == runtime.GOOS {return homeWindows()}// Unix-like system, so just assume Unixreturn homeUnix()}func homeUnix() (string, error) {// First prefer the HOME environmental variableif home := os.Getenv("HOME"); home != "" {return home, nil}// If that fails, try the shellvar stdout bytes.Buffercmd := exec.Command("sh", "-c", "eval echo ~$USER")cmd.Stdout = &stdoutif err := cmd.Run(); err != nil {return "", err}result := strings.TrimSpace(stdout.String())if result == "" {return "", errors.New("blank output when reading home directory")}return result, nil}func homeWindows() (string, error) {drive := os.Getenv("HOMEDRIVE")path := os.Getenv("HOMEPATH")home := drive + pathif drive == "" || path == "" {home = os.Getenv("USERPROFILE")}if home == "" {return "", errors.New("HOMEDRIVE, HOMEPATH, and USERPROFILE are blank")}return home, nil}

參考

  • Obtain user's home directory
  • go-homedir
  • 一些有用的工具函數
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.