组合绝对路径和相对路径以获得新的绝对路径

Ale*_*uer 15 path go

我正在编写一个程序,其中一个组件必须能够获取它给出的路径(例如/help/index.html,或/help/)和基于该位置的相对路径(例如../otherpage/index.html,或sub/dir/of/help/,或help2.html)并产生绝对路径相对路径暗示.请考虑以下目录树.

/
index.html
content.txt
help/
    help1.html
    help2.html
Run Code Online (Sandbox Code Playgroud)

该文件index.html包含类似的链接help/help1.html.程序通过/或者/index.html将它与help/help1.htmlget 结合起来/help/help1.html.

同样,该文件/help/help1.html具有链接../content.txt,程序需要从该链接返回/content.txt.有合理的方法吗?

谢谢.:)

编辑:谢谢Stephen Weinberg!对于未来的每个人,这是我使用的代码.

func join(source, target string) string {
    if path.IsAbs(target) {
        return target
    }
    return path.Join(path.Dir(source), target)
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*erg 23

path.Join与使用时path.Dir应该做你想要什么.有关交互式示例,请参阅http://golang.org/pkg/path/#example_Join.

path.Join(path.Dir("/help/help1.html"), "../content.txt")
Run Code Online (Sandbox Code Playgroud)

这将返回/content.txt.