package projects import ( "errors" "fmt" "net" "net/url" "strconv" "time" giturl "github.com/whilp/git-urls" ) const defNetDialTimeoutSecs = 5 type GitProto int const ( GitProtoSSH GitProto = iota GitProtoHTTP ) var ErrUnknownHost error = errors.New("no addresses found for host") func (p *Project) CheckHost(proto GitProto) error { switch proto { case GitProtoHTTP: return p.checkHTTPRemote() case GitProtoSSH: return p.checkSSHRemote() } return errors.New("unknown git protocol") } func (p *Project) checkHTTPRemote() error { u, err := giturl.Parse(p.HTTPURLToRepo) if err == nil { err = p.checkHost(u) } return err } func (p *Project) checkSSHRemote() error { u, err := giturl.Parse(p.SSHURLToRepo) if err == nil { err = p.checkHost(u) } return err } func (p *Project) checkHost(u *url.URL) error { var port int if u.Port() == "" { switch u.Scheme { case "http": port = 80 case "ssh": port = 22 case "https": port = 443 } } else { port, _ = strconv.Atoi(u.Port()) } d, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", u.Hostname(), port), defNetDialTimeoutSecs*time.Second) if err == nil { _, err = d.Write([]byte("ok")) d.Close() } return err }