gatus/client/client.go

83 lines
1.8 KiB
Go
Raw Normal View History

package client
import (
"crypto/tls"
"net"
"net/http"
"time"
"github.com/go-ping/ping"
)
var (
2020-10-23 22:29:20 +02:00
secureHTTPClient *http.Client
insecureHTTPClient *http.Client
2021-01-13 03:26:28 +01:00
pingTimeout = 5 * time.Second
)
2020-10-23 22:29:20 +02:00
// GetHTTPClient returns the shared HTTP client
func GetHTTPClient(insecure bool) *http.Client {
if insecure {
2020-10-23 22:29:20 +02:00
if insecureHTTPClient == nil {
insecureHTTPClient = &http.Client{
2021-01-05 05:38:47 +01:00
Timeout: 10 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 20,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
}
2020-10-23 22:29:20 +02:00
return insecureHTTPClient
}
if secureHTTPClient == nil {
secureHTTPClient = &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 20,
},
}
}
2020-10-23 22:29:20 +02:00
return secureHTTPClient
}
// CanCreateTCPConnection checks whether a connection can be established with a TCP service
func CanCreateTCPConnection(address string) bool {
conn, err := net.DialTimeout("tcp", address, 5*time.Second)
if err != nil {
return false
}
_ = conn.Close()
return true
}
// Ping checks if an address can be pinged and returns the round-trip time if the address can be pinged
//
// Note that this function takes at least 100ms, even if the address is 127.0.0.1
func Ping(address string) (bool, time.Duration) {
pinger, err := ping.NewPinger(address)
if err != nil {
return false, 0
}
pinger.Count = 1
2021-01-13 03:26:28 +01:00
pinger.Timeout = pingTimeout
pinger.SetNetwork("ip4")
pinger.SetPrivileged(true)
err = pinger.Run()
if err != nil {
return false, 0
}
if pinger.Statistics() != nil {
// If the packet loss is 100, it means that the packet didn't reach the host
if pinger.Statistics().PacketLoss == 100 {
return false, pinger.Timeout
}
return true, pinger.Statistics().MaxRtt
}
return true, 0
}