亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用golang提取基本url

如何使用golang提取基本url

Go
慕勒3428872 2022-12-19 10:53:45
給定一個 url 字符串,如何只檢索基本 url(即 protocol://host:port)例如https://example.com/user/1000 => https://example.comhttps://localhost:8080/user/1000/profile => https://localhost:8080我試過解析 url,url.Parse()但net/url似乎沒有返回基本 url 的方法。我可以嘗試附加 url 的各個部分來獲取基本 url,但我只是想檢查是否有更好的替代方法。
查看完整描述

2 回答

?
慕神8447489

TA貢獻1780條經驗 獲得超1個贊

我會使用url.Parse(), 解析它,并將結果中不需要的字段歸零,即Path,RawQueryFragment。然后可以使用 獲取結果(基本 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


查看完整回答
反對 回復 2022-12-19
?
蕪湖不蕪

TA貢獻1796條經驗 獲得超7個贊

你可以試試


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)

    }

}


查看完整回答
反對 回復 2022-12-19
  • 2 回答
  • 0 關注
  • 289 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號