git-project-manager/internal/remotes/remotes_net.go

79 lines
1.2 KiB
Go

package remotes
import (
"errors"
"fmt"
"net"
"net/url"
"strconv"
"time"
giturl "github.com/whilp/git-urls"
)
const defNetDialTimeoutSecs = 5
type GitlabProto int
const (
GitlabProtoSSH GitlabProto = iota
GitlabProtoHTTP
)
var (
ErrUnknownHost error = errors.New("No addresses found for host")
)
func (p *Project) CheckHost(proto GitlabProto) error {
switch proto {
case GitlabProtoHTTP:
return p.checkHTTPRemote()
case GitlabProtoSSH:
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
}