【问题标题】:Convert relative to absolute URLs in Go在 Go 中将相对 URL 转换为绝对 URL
【发布时间】:2019-05-10 13:34:30
【问题描述】:

我正在编写一个小型网络爬虫,而我正在爬取的网站上的许多链接都是相对的(例如,它们是 /robots.txt)。如何将这些相对 URL 转换为绝对 URL(所以 /robots.txt => http://google.com/robots.txt)? Go 有内置的方法吗?

【问题讨论】:

    标签: url go relative-url


    【解决方案1】:

    是的,标准库可以通过net/url 包做到这一点。示例(来自标准库):

    package main
    
    import (
        "fmt"
        "log"
        "net/url"
    )
    
    func main() {
        u, err := url.Parse("../../..//search?q=dotnet")
        if err != nil {
            log.Fatal(err)
        }
        base, err := url.Parse("http://example.com/directory/")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(base.ResolveReference(u))
    }
    

    请注意,您只需要解析一次绝对 URL,然后您就可以一遍又一遍地重复使用它。

    【讨论】:

    • 谢谢@Not_a_Golfer。好主意。
    【解决方案2】:

    在@Not_a_Golfer 的解决方案之上。

    您还可以使用base URL 的Parse 方法提供相对或绝对URL。

    package main
    
    import (
        "fmt"
        "log"
        "net/url"
    )
    
    func main() {
        // parse only base url
        base, err := url.Parse("http://example.com/directory/")
        if err != nil {
            log.Fatal(err)
        }
    
        // and then use it to parse relative URLs
        u, err := base.Parse("../../..//search?q=dotnet")
        if err != nil {
            log.Fatal(err)
        }
    
        fmt.Println(u.String())
    }
    

    试试Go Playground

    【讨论】:

      猜你喜欢
      • 2014-12-12
      • 2021-07-28
      • 2011-01-01
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 2015-06-28
      • 2011-08-04
      相关资源
      最近更新 更多