2 回答
TA贡献1811条经验 获得超5个赞
下面是使用 net、net/url 和字符串包的简单方法。
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
TA贡献1859条经验 获得超6个赞
您可以使用专用的 git url 解析器,如下所示:
package utils
import (
"os/exec"
giturl "github.com/armosec/go-git-url"
)
func isGitURL(repo string) bool {
_, err := giturl.NewGitURL(repo) // parse URL, returns error if none git url
return err == nil
}
//CloneRepo clones a repo lol
func CloneRepo(args []string) {
//repo URL
repo := args[0]
//verify that is an actual github repo URL
if !isGitURL(repo) {
// return
}
//Clones Repo
exec.Command("git", "clone", repo).Run()
}
这将为您提供优势,不仅可以验证它是否是git存储库,而且您可以运行更多验证,以便作为所有者(),存储库()等。GetOwner()GetRepo()
- 2 回答
- 0 关注
- 95 浏览
添加回答
举报