英文:
Combine absolute path and relative path to get a new absolute path
问题
我正在编写一个程序,其中一个组件必须能够接受给定的路径(例如/help/index.html
或/help/
)和基于该位置的相对路径(例如../otherpage/index.html
、sub/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
。有没有合理的方法来实现这个?
谢谢。
编辑: 感谢Stephen Weinberg!对于未来的人们,这是我使用的代码。
func join(source, target string) string {
if path.IsAbs(target) {
return target
}
return path.Join(path.Dir(source), target)
}
英文:
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)
}
答案1
得分: 32
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
.
英文:
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
.
答案2
得分: 4
Stephen的答案是正确的,但我想补充一些内容,以节省未来读者的时间:
你应该注意到path包中的函数假设分隔符是/
。当使用上面的示例时,我一直得到输出.
,因为我使用了Windows的文件路径,即\
。
如果你不是在处理URL,考虑使用filepath包,它使用操作系统的目录分隔符。
例如,在Windows上运行时:
path.Dir("C:\\Users\\Darren\\Desktop\\file.txt")
filepath.Dir("C:\\Users\\Darren\\Desktop\\file.txt")
返回:
.
C:\Users\Darren\Desktop
英文:
Stephen's answer is correct, but I wanted to add something to save future readers some time:
You should note functions within the path package assume the separator is /
. When using the example above, I kept getting the output .
since I had a Window's file path using \
.
If you're not manipulating URLs, consider using the filepath package which uses the OS's directory separator.
E.g. When running on Windows:
path.Dir("C:\\Users\\Darren\\Desktop\\file.txt")
filepath.Dir("C:\\Users\\Darren\\Desktop\\file.txt")
Returns:
.
C:\Users\Darren\Desktop
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论