确保URI有效 [英] Ensure a URI is valid
问题描述
我正在尝试确保传递给go程序的URL有效.但是,我似乎无法解决.我以为我可以通过 url.Parse
喂它,但这似乎没用.
I'm trying to ensure that URLs passed to my go program are valid. However, I can't seem to work out how to. I thought I could just feed it through url.Parse
, but that doesn't seem to do the job.
package main
import (
"fmt"
"net/url"
)
func main() {
url, err := url.Parse("http:::/not.valid/a//a??a?b=&&c#hi")
if err != nil {
panic(err)
}
fmt.Println("It's valid!", url.String())
}
我可以使用 filter_var 的内容吗?
推荐答案
您可以检查您的URL是否具有Scheme,Host和/或Path.
You can check that your URL has a Scheme, Host, and/or a Path.
如果检查返回的URL,则可以看到无效部分已插入不透明数据部分(从某种意义上讲,它是有效的).
If you inspect the URL returned, you can see that the invalid part is inserted into the Opaque data section (so in a sense, it is valid).
url.URL{Scheme:"http", Opaque:"::/not.valid/a//a", Host:"", Path:"", RawQuery:"?a?b=&&c", Fragment:"hi"}
如果您解析一个URL并且没有Scheme,Host和Path,您可能会认为它无效.(尽管没有路径的主机通常可以,因为它暗示/
,所以您需要检查一下)
If you parse a URL and don't have a Scheme, Host and Path you can probably assume it's not valid. (though a host without a path is often OK, since it implies /
, so you need to check for that)
u, err := url.Parse("http:::/not.valid/a//a??a?b=&&c#hi")
if err != nil {
log.Fatal(err)
}
if u.Scheme == "" || u.Host == "" || u.Path == "" {
log.Fatal("invalid URL")
}
这篇关于确保URI有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!