Issue
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
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
Answered By – chuckx
Answer Checked By – Marie Seifert (GoLangFix Admin)