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)
}
In simple words, an absolute path refers to the same location in a file system relative to the root directory, whereas a relative path points to a specific location in a file system relative to the current directory you are working on.
Combines two strings into a path. Combine(String, String, String) Combines three strings into a path. Combine(String, String, String, String) Combines four strings into a path.
An absolute path is defined as specifying the location of a file or directory from the root directory(/). In other words,we can say that an absolute path is a complete path from start of actual file system from / directory. Relative path is defined as the path related to the present working directly(pwd).
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With