验证我的回购实际上是 Go 中的 github 回购 URL

verify that my repo it's in fact a github repo URL in Go

Go 中是否有一种方法可以验证回购类型字符串实际上是实际的 Github 回购 URL?

我正在 运行 复制这个克隆一个 repo 的代码,但是在我 运行 exec.Command("git", "clone", repo) 和我想确保 repo 有效。

    package utils

    import (
        "os/exec"
    )

    //CloneRepo clones a repo lol
    func CloneRepo(args []string) {

        //repo URL
        repo := args[0]

        //verify that is an actual github repo URL

        //Clones Repo
        exec.Command("git", "clone", repo).Run()

    }

这是使用 net, net/url, and 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

Go Playground

您可以使用如下专用 git url parser

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()) 等等