【问题标题】:Combine absolute path and relative path to get a new absolute path结合绝对路径和相对路径得到新的绝对路径
【发布时间】:2012-10-16 05:03:29
【问题描述】:

我正在编写一个程序,其中一个组件必须能够采用给定的路径(例如/help/index.html,或/help/)和基于该位置的相对路径,(例如@ 987654324@, or sub/dir/of/help/, or 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。有没有合理的方法来做到这一点?

谢谢。 :)

编辑:感谢斯蒂芬·温伯格!对于大家from the future,这是我使用的代码。

func join(source, target string) string {
    if path.IsAbs(target) {
        return target
    }
    return path.Join(path.Dir(source), target)
}

【问题讨论】:

    标签: path go


    【解决方案1】:

    path.Join 与 path.Dir 一起使用时应该可以满足您的需求。有关交互式示例,请参阅 http://golang.org/pkg/path/#example_Join。

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

    这将返回/content.txt。

    【讨论】:

    • 谢谢!它并没有完全达到我想要的效果,但我能够使用其他路径实用程序将它包装在一个小函数中。对于from the future 的任何人,都在这里。 func join(source, target string) string { if path.IsAbs(target) { return target } return path.Join(path.Dir(source), target) }
    • 我现在知道这不是您想要的。我更新了我的答案。
    • 再次感谢您;由于绝对路径被奇怪地解释,我不得不添加一个 if 语句。我对 StackOverflow 的特定品牌 markdown 仍然不熟悉,所以我只是在顶部添加了代码块。
    • @SashaCrofter,将要排版的块作为代码括在一对反引号(`...`)中。请注意,您仍然不能在 cmets 中拥有多行代码块,因此您修改帖子的想法无论如何都是正确的。
    • 这已损坏:例如尝试将 http://example.com/a/b 与 / 合并:它应该是 http://example.com/ 但它返回 http://example.com/a。
    【解决方案2】:

    Stephen's answer 是正确的,但我想添加一些内容以节省未来读者的时间:

    您应该注意path package 中的函数假设分隔符是/。使用上面的示例时,我一直得到输出 .,因为我有一个使用 \ 的 Window 文件路径。

    如果您不处理 URL,请考虑使用filepath package,它使用操作系统的目录分隔符。

    例如在 Windows 上运行时:

    path.Dir("C:\\Users\\Darren\\Desktop\\file.txt")
    filepath.Dir("C:\\Users\\Darren\\Desktop\\file.txt")
    

    返回:

    .
    C:\Users\Darren\Desktop
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-15
      • 2013-07-14
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-11
      • 2013-04-17
      相关资源
      最近更新 更多