四季花海
下面是使用 net、net/url 和字符串包的简单方法。package mainimport ( "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: trueURL: "http://github.com/bar/foo", is GitHub URL: trueURL: "http://github.com.evil.com", is GitHub URL: falseURL: "http://github.com:8080/nonstandard/port", is GitHub URL: trueURL: "http://other.com", is GitHub URL: falseURL: "not a valid URL", is GitHub URL: false