2 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
我會(huì)使用url.Parse()
, 解析它,并將結(jié)果中不需要的字段歸零,即Path
,RawQuery
和Fragment
。然后可以使用 獲取結(jié)果(基本 URL)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

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超7個(gè)贊
你可以試試
u, _ := url.Parse("https://example.com/user/1000")
val := fmt.Sprintf("%s://%s", u.Scheme, u.Host)
在一般情況下,以下內(nèi)容可能更有用。
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)
}
}
- 2 回答
- 0 關(guān)注
- 285 瀏覽
添加回答
舉報(bào)