【问题标题】:verify that my repo it's in fact a github repo URL in Go验证我的 repo 它实际上是 Go 中的 github repo URL
【发布时间】:2021-06-02 16:49:14
【问题描述】:

Go 中是否有方法来验证 repo 类型字符串实际上是一个实际的 Github repo 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()

    }

【问题讨论】:

  • 我对您的问题进行了小幅修改,这样它就不会要求包推荐,这会使 Stackoverflow 偏离主题。

标签: regex go package goland


【解决方案1】:

这是使用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

【讨论】:

  • strings.Index(u.Host, "github.com") == 0 报告 github.com.evil.net 的误报。使用net.SplitHostPort 和普通字符串比较来忽略端口。
  • 感谢反馈,更新了答案。
猜你喜欢
  • 1970-01-01
  • 2017-03-01
  • 1970-01-01
  • 2013-08-20
  • 2012-02-25
  • 2013-08-14
  • 2012-02-19
  • 1970-01-01
  • 2013-03-08
相关资源
最近更新 更多