组合绝对路径和相对路径以获得新的绝对路径 [英] Combine absolute path and relative path to get a new absolute path

查看:191
本文介绍了组合绝对路径和相对路径以获得新的绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  / 
index.html
content.txt
帮助/
help1.html
help2.html

文件 index.html 包含一个链接,如 help / help1.html 。该程序通过 / /index.html ,并与 help / help1结合.html 来获取 /help/help1.html



同样, /help/help1.html 包含链接 ../ content.txt ,程序需要返回 /content.txt 。有没有合理的方法来做到这一点?



谢谢。 :)



编辑:谢谢Stephen Weinberg! 来自未来,以下是我使用的代码。

  func join(source,target string)string {
如果path.IsAbs(target){
返回目标
}
返回path.Join(path.Dir(source),target)
}


解决方案 path.Join path.Dir 一起使用时应该做你想做的事。有关交互式示例,请参阅 http://golang.org/pkg/path/#example_Join

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

这将返回 /content.txt


I'm writing a program in which one of the components must be able to take a path it is given (such as /help/index.html, or /help/) and a relative path based on that location, (such as ../otherpage/index.html, or sub/dir/of/help/, or help2.html) and produce the absolute path implied by the relative path. Consider the following directory tree.

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

The file index.html contains a link like help/help1.html. The program is passed / or /index.html, and combines it with help/help1.html to get /help/help1.html.

Similarly, the file /help/help1.html has the link ../content.txt, from which the program needs to return /content.txt. Is there a reasonable way to do this?

Thank you. :)

Edit: Thank you to Stephen Weinberg! For everyone from the future, here's the code I used.

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

解决方案

The path.Join when used with path.Dir should do what you want. See http://golang.org/pkg/path/#example_Join for an interactive example.

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

This will return /content.txt.

这篇关于组合绝对路径和相对路径以获得新的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆