duanli5662 2018-09-13 03:20
浏览 43
已采纳

给定两个绝对URI,找到它们之间的相对路径

Is there a function in go standard library that lets me do this

a = 'www.my.com/your/stuff'
b = 'www.my.com/your/stuff/123/4'

function(b,a) // /123/4 

or

function(URL(b),URL(a)) // /123/4

The following is probably defined in this case

function(a,b) // error ? or ../../

I'm aware that I can use path package for this. But it cannot work in many cases where there is query param, file extension etc.

Basically I'm looking for a path.resolve counterpart for URL

  • 写回答

1条回答 默认 最新

  • douchen7555 2018-09-13 03:44
    关注

    It turns out that the path/filepath package can do this for you. If you ignore the fact that these are URLs and instead treat them like paths, you can use filepath.Rel():

    package main
    
    import (
        "fmt"
        "path/filepath"
    )
    
    func main() {
        base := "www.my.com/your/stuff"
        target := "www.my.com/your/stuff/123/4"
        rel, _ := filepath.Rel(base, target)
        fmt.Println(rel) // prints "123/4"
    }
    

    Playground: https://play.golang.org/p/nnF9zfFAFfc

    If you want to treat these paths as actual URLs, you should probably use the net/url package to first parse the path as a URL, then extract the path and use filepath.Rel() on that. This allows you to properly deal with things like queries in the URL string, which would trip up filepath, like so:

    package main
    
    import (
        "fmt"
        "path/filepath"
        "net/url"
    )
    
    func main() {
        url1, _ := url.Parse("http://www.my.com/your/stuff")
        url2, _ := url.Parse("http://www.my.com/your/stuff/123/4?query=test")
    
        base := url1.Path
        target := url2.Path
    
        rel, _ := filepath.Rel(base, target)
        fmt.Println(base)   // "/your/stuff"
        fmt.Println(target) // "/your/stuff/123/4"
        fmt.Println(rel)    // "123/4"
    }
    

    Playground: https://play.golang.org/p/gnZfk0t8GOZ

    As a bonus, filepath.Rel() is smart enough to handle relative paths in the other direction, too:

    rel, _ = filepath.Rel(target, base) // rel is now "../.."
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”