如何使用 golang 提取基数 url

How to extract base url using golang

给定一个 url 字符串,如何只检索基数 url(即协议://主机:端口)

例如

https://example.com/user/1000 => https://example.com

https://localhost:8080/user/1000/profile => https://localhost:8080

我尝试用 url.Parse() 解析 url 但 net/url 似乎没有 returns 基础 url 的方法.我可以尝试附加 url 的各个部分以获得基础 url 但我只是想检查是否有更好的替代方法。

我会使用 url.Parse(), and zero the fields you don't want in the result, namely Path, RawQuery and Fragment. Then the result (base URL) can be acquired using URL.String() 解析它。

例如:

u, err := url.Parse("https://user@pass:localhost:8080/user/1000/profile?p=n#abc")
if err != nil {
    panic(err)
}
fmt.Println(u)
u.Path = ""
u.RawQuery = ""
u.Fragment = ""
fmt.Println(u)
fmt.Println(u.String())

这将输出(在 Go Playground 上尝试):

https://user@pass:localhost:8080/user/1000/profile?p=n#abc
https://user@pass:localhost:8080
https://user@pass:localhost:8080

你可以试试

u, _ := url.Parse("https://example.com/user/1000")
val := fmt.Sprintf("%s://%s", u.Scheme, u.Host)

以下内容在一般情况下可能更有用。

rawURL := "https://user:pass@localhost:8080/user/1000/profile?p=n#abc"
u, _ := url.Parse(rawURL)
psw, pswSet := u.User.Password()
for _, d := range []struct {
    actual   any
    expected any
}{
    {u.Scheme, "https"},
    {u.User.Username(), "user"},
    {psw, "pass"},
    {pswSet, true},
    {u.Host, "localhost:8080"},
    {u.Path, "/user/1000/profile"},
    {u.Port(), "8080"},
    {u.RawPath, ""},
    {u.RawQuery, "p=n"},
    {u.Fragment, "abc"},
    {u.RawFragment, ""},
    {u.RequestURI(), "/user/1000/profile?p=n"},
    {u.String(), rawURL},
    {fmt.Sprintf("%s://%s", u.Scheme, u.Host), "https://localhost:8080"},
} {
    if d.actual != d.expected {
        t.Fatalf("%s\n%s\n", d.actual, d.expected)
    }
}

go-playground