Golang Get the user home directory path

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Os/user

In general, we can use os/user the functions provided by the package Current() to obtain user information:

User, Err: = user. Current () if nil = = Err {return user. Homedir, nil}

But this approach cannot cross-compile completely across platforms and requires CGO under Darwin to work properly.

Improved

In order to solve this problem, we need to make a little bit of enhancement and os/user get it through the environment variables and commands when we get the failure:

Home returns the home directory for the executing user.////this uses a os-specific method for discovering the Home di rectory.//An error was 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) {//F Irst 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}

Reference

    • Obtain user ' s home directory
    • Go-homedir
    • Some useful tool functions
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.