验证我的 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

解决方法

这是使用 netnet/urlstrings 包的简单方法。

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