git-project-manager/internal/remotes/projects/projects_net.go

77 lines
1.2 KiB
Go
Raw Permalink Normal View History

2024-01-15 20:39:35 +00:00
package projects
2023-12-10 04:19:19 +00:00
import (
"errors"
"fmt"
"net"
"net/url"
"strconv"
"time"
giturl "github.com/whilp/git-urls"
)
const defNetDialTimeoutSecs = 5
2024-01-16 17:48:42 +00:00
type GitProto int
2023-12-10 04:19:19 +00:00
const (
2024-01-16 17:48:42 +00:00
GitProtoSSH GitProto = iota
GitProtoHTTP
2023-12-10 04:19:19 +00:00
)
var ErrUnknownHost error = errors.New("no addresses found for host")
2023-12-10 04:19:19 +00:00
2024-01-16 17:48:42 +00:00
func (p *Project) CheckHost(proto GitProto) error {
2023-12-10 04:19:19 +00:00
switch proto {
2024-01-16 17:48:42 +00:00
case GitProtoHTTP:
2023-12-10 04:19:19 +00:00
return p.checkHTTPRemote()
2024-01-16 17:48:42 +00:00
case GitProtoSSH:
2023-12-10 04:19:19 +00:00
return p.checkSSHRemote()
}
return errors.New("unknown git protocol")
2023-12-10 04:19:19 +00:00
}
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
}