path - 将波浪号展开到主目录

标签 path go

我有一个程序接受将在其中创建文件的目标文件夹。我的程序应该能够处理绝对路径和相对路径。我的问题是我不知道如何将 ~ 展开到主目录。

我扩展目的地的功能如下所示。如果给定的路径是绝对路径,则它什么也不做,否则它将相对路径与当前工作目录连接。

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/

相关文章:

python - 如何安装 Geckodriver?

python - Django 传递字符串参数

Python:查找连接到n(元组)的所有节点

node.js - Golang 中的 package.json 等价物

go - 为接口(interface)运行类型断言解码编译器输出

postgresql - 创建或更新未在GORM中返回更新后的值

python - 未找到命令 Python2

php - MySQL 中有等效的 basename() 吗?

docker - Golang docker 多阶段构建运行失败 : exec: "go": executable file not found in $PATH

go - 如何解决Go channel 死锁?