Combine absolute path and relative path to get a new absolute path

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

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 Like

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 .

Refer: combine-absolute-path-and-relative-path-to-get-a-new-absolute-path