如何解决验证我的 repo 它实际上是 Go 中的 github repo URL
Go 中是否有一种方法可以验证 repo 类型字符串实际上是实际的 Github 存储库 URL?
我正在运行这个克隆 repo 的代码,但在我运行 exec.Command("git","clone",repo) 之前,我想确保 repo 是有效的。
http://www.example.com/brands/567.jpg // http://www.example.com
https://www.example.org/photo.png // https://www.example.org
http://example.net/789 // http://example.net
解决方法
这是使用 net
、net/url
和 strings
包的简单方法。
package main
import (
"fmt"
"net"
"net/url"
"strings"
)
func isGitHubURL(input string) bool {
u,err := url.Parse(input)
if err != nil {
return false
}
host := u.Host
if strings.Contains(host,":") {
host,_,err = net.SplitHostPort(host)
if err != nil {
return false
}
}
return host == "github.com"
}
func main() {
urls := []string{
"https://github.com/foo/bar","http://github.com/bar/foo","http://github.com.evil.com","http://github.com:8080/nonstandard/port","http://other.com","not a valid URL",}
for _,url := range urls {
fmt.Printf("URL: \"%s\",is GitHub URL: %v\n",url,isGitHubURL(url))
}
}
输出:
URL: "https://github.com/foo/bar",is GitHub URL: true
URL: "http://github.com/bar/foo",is GitHub URL: true
URL: "http://github.com.evil.com",is GitHub URL: false
URL: "http://github.com:8080/nonstandard/port",is GitHub URL: true
URL: "http://other.com",is GitHub URL: false
URL: "not a valid URL",is GitHub URL: false
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。