如何在golang中解析相对路径到绝对路径?

问题描述:

节点中是否有类似"path.resolve"的api?还是有什么可以做的?

Is there a api like 'path.resolve' in node? Or something can do the same?

例如(nodejs代码): path.resolve("~/sample.sh") 应该得到:/home/currentuser/sample.sh

For Example (nodejs code): path.resolve("~/sample.sh") Should got: /home/currentuser/sample.sh

解决~(表示用户住所)是另一回事,通常是由外壳来解决.有关详细信息,请参见将波浪线扩展到主目录.

Resolving ~ (denoting the user home) is a different story, and usually it's the shell that resolves this. For details see Expand tilde to home directory.

如果您想通过Go代码进行操作,则可以使用 user.Current() 函数可获取有关当前用户的详细信息,包括其主文件夹(将为User.HomeDir).但是,您仍然必须自己替换它.

If you want to do it from Go code, you may use the user.Current() function to get details about the current user, including its home folder which will be User.HomeDir. But still, you'll have to handle replacing this yourself.

原始答案如下.

您可以使用 path.Join()

You may use path.Join() or filepath.Join().

例如:

base := "/home/bob"
fmt.Println(path.Join(base, "work/go", "src/github.com"))

输出:

/home/bob/work/go/src/github.com

您可以使用 path.Clean() .和双点...

You may use path.Clean() and filepath.Clean() to "remove" dots . and double dots .. from your path.

您可以使用 filepath.Abs() 来解析相对路径并获取绝对路径(如果不是绝对目录,则在工作目录之前). filepath.Abs()也会在结果上调用Clean().

You may use filepath.Abs() to resolve relative paths and get an absolute (prepending the working directory if it's not absolute). filepath.Abs() also calls Clean() on the result.

例如:

fmt.Println(filepath.Abs("/home/bob/../alice"))

输出:

/home/alice <nil>

去游乐场上尝试示例.

请参阅相关问题:从相对路径解析绝​​对路径