我有一个程序接受将在其中创建文件的目标文件夹。我的程序应该能够处理绝对路径和相对路径。我的问题是我不知道如何将 ~
展开到主目录。
我扩展目的地的功能如下所示。如果给定的路径是绝对路径,则它什么也不做,否则它将相对路径与当前工作目录连接。
import "path"
import "os"
// var destination *String is the user input
func expandPath() {
if path.IsAbs(*destination) {
return
}
cwd, err := os.Getwd()
checkError(err)
*destination = path.Join(cwd, *destination)
}
自从 path.Join
不展开 ~
如果用户传递类似 ~/Downloads
之类的东西作为目的地,它就不起作用。
我应该如何跨平台解决这个问题?
最佳答案
Go 提供了包 os/user ,它允许您获取当前用户,以及任何用户的主目录:
usr, _ := user.Current()
dir := usr.HomeDir
然后,使用 path/filepath将两个字符串组合到有效路径:
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:])
}
(注意 user.Current() 没有在 go playground 中实现(可能是出于安全原因),所以我不能给出一个易于运行的示例)。
关于path - 将波浪号展开到主目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17609732/