解析带端口和不带方案的 URL

我正在尝试解析 Go 中的 URL 并从 URL 获取主机和方案。但是,在解析带有端口且没有方案的 URL 时,我得到了意想不到的结果。


u, err := url.ParseRequestURI("hello.com:81")

fmt.Println("host :",u.Host)

fmt.Println("scheme :",u.Scheme)


我得到了意想不到的结果


host :

scheme: hello.com

我想要这个


host : hello.com:80

scheme:


www说
浏览 160回答 3
3回答

三国纷争

net.URL 文档中定义的格式是以下之一:[scheme:][//[userinfo@]host][/]path[?query][#fragment]scheme:opaque[?query][#fragment]是可选的scheme:,但双斜杠是该host字段的一部分。这意味着您输入的有效字符串是://hello.com:81这将导致:u, _ := url.Parse("//hello.com:81")fmt.Println("host:", u.Host)// Output: host: hello.com:81你需要把你的输入变成有效的东西。如果您知道字符串从不包含该方案,您可以简单地在前面加上//. 如果您有时只指定了一个方案,您可以尝试有条件地操作输入。

繁星淼淼

如果您需要处理仅包含主机和端口(没有方案和其他参数)的 URL,您可以使用以下代码:&nbsp; &nbsp;host, port, err := net.SplitHostPort("hello.com:81")&nbsp; &nbsp;fmt.Println("host:", host, "port:", port, "err:", err)&nbsp; &nbsp;// output: host: hello.com port: 81 err <nil>注意SplitHostPort()不适合解析标准网址(符合[scheme:][//[userinfo@]host][/]path[?query][#fragment])

拉风的咖菲猫

根据 go doc,表示的一般 url 形式为:[scheme:][//[userinfo@]host][/]path[?query][#fragment]方案后不以斜杠开头的 URL 被解释为:scheme:opaque[?query][#fragment]您的 URL 被解析为第二种格式。您可以使用此方法获得预期的结果。在函数中,如果 URL 中没有方案,我们添加它,然后再次解析它以获得预期的结果。func parseRawURL(rawurl string) (domain string, scheme string, err error) {&nbsp; &nbsp; u, err := url.ParseRequestURI(rawurl)&nbsp; &nbsp; if err != nil || u.Host == "" {&nbsp; &nbsp; &nbsp; &nbsp; u, repErr := url.ParseRequestURI("https://" + rawurl)&nbsp; &nbsp; &nbsp; &nbsp; if repErr != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("Could not parse raw url: %s, error: %v", rawurl, err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; domain = u.Host&nbsp; &nbsp; &nbsp; &nbsp; err = nil&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; domain = u.Host&nbsp; &nbsp; scheme = u.Scheme&nbsp; &nbsp; return}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go