第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何使用golang提取基本url

如何使用golang提取基本url

Go
慕勒3428872 2022-12-19 10:53:45
給定一個(gè) 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 的各個(gè)部分來獲取基本 url,但我只是想檢查是否有更好的替代方法。
查看完整描述

2 回答

?
慕神8447489

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊

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


查看完整回答
反對(duì) 回復(fù) 2022-12-19
?
蕪湖不蕪

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)

    }

}


查看完整回答
反對(duì) 回復(fù) 2022-12-19
  • 2 回答
  • 0 關(guān)注
  • 285 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)