你可以试试
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)
}
}