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
.
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