Expand tilde to home directory

Go provides the package os/user, which allows you to get the current user, and for any user, their home directory:

usr, _ := user.Current()
dir := usr.HomeDir

Then, use path/filepath to combine both strings to a valid path:

if path == "~" {
    // In case of "~", which won't be caught by the "else if"
    path = dir
} else if strings.HasPrefix(path, "~/") {
    // Use strings.HasPrefix so we don't match paths like
    // "/something/~/something/"
    path = filepath.Join(dir, path[2:])
}

(Note that user.Current() is not implemented in the go playground (likely for security reasons), so I can’t give an easily runnable example).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)