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

亚历山大·鲍尔(Alexander Bauer):

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

/
index.html
content.txt
help/
    help1.html
    help2.html

该文件index.html包含一个类似的链接help/help1.html该计划获得通过//index.html,并将其与结合help/help1.html来获得/help/help1.html

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

谢谢。:)

编辑:谢谢斯蒂芬·温伯格!对于未来的每个人,这是我使用的代码。

func join(source, target string) string {
    if path.IsAbs(target) {
        return target
    }
    return path.Join(path.Dir(source), target)
}
斯蒂芬·温伯格(Stephen Weinberg):

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

path.Join(path.Dir("/help/help1.html"), "../content.txt")

这将返回/content.txt

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章