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

Is there a method in Go to verify that a repo type string is in fact an actual Github repo URL?

I'm running this code that clones a repo, but before I run exec.Command("git", "clone", repo) and i want to make sure that repo is valid.

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

    }


Solution 1:[1]

Here's a simple approach using the net, net/url, and strings packages.

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))
    }
}

Output:

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

Solution 2:[2]

You can use a dedicated git url parser as following:

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

This will give you the advantage of not only validating if it is a git repo, but you can run more validations so as owner (GetOwner()), repo (GetRepo()) etc.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 David Wer