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