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

后端 未结 2 1244
闹比i
闹比i 2021-02-18 20:26

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

相关标签:
2条回答
  • 2021-02-18 20:52

    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
    
    0 讨论(0)
  • 2021-02-18 21:17

    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.

    0 讨论(0)
提交回复
热议问题