給定一個 url 字串,如何只檢索基本 url(即協議://主機:埠)
例如
https://example.com/user/1000 => https://example.com
https://localhost:8080/user/1000/profile => https://localhost:8080
我嘗試使用決議 url,url.Parse()但net/url似乎沒有回傳基本 url 的方法。我可以嘗試附加 url 的各個部分以獲取基本 url,但我只是想檢查是否有更好的替代方法。
uj5u.com熱心網友回復:
我會使用 , 來決議它url.Parse(),并將結果中不需要的欄位歸零,即Path,RawQuery和Fragment。然后可以使用 獲取結果(基本 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
uj5u.com熱心網友回復:
你可以試試
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/483947.html
