added ping latency to healthcheck result

This commit is contained in:
yusing
2024-11-30 06:43:47 +08:00
parent 497879fb4b
commit fb9de4c4ad
6 changed files with 50 additions and 19 deletions

View File

@@ -4,6 +4,7 @@ import (
"crypto/tls"
"errors"
"net/http"
"time"
"github.com/yusing/go-proxy/internal/net/types"
"github.com/yusing/go-proxy/internal/watcher/health"
@@ -40,7 +41,7 @@ func NewHTTPHealthChecker(url types.URL, config *health.HealthCheckConfig) healt
return NewHTTPHealthMonitor(url, config)
}
func (mon *HTTPHealthMonitor) CheckHealth() (healthy bool, detail string, err error) {
func (mon *HTTPHealthMonitor) CheckHealth() (result *health.HealthCheckResult, err error) {
ctx, cancel := mon.ContextWithTimeout("ping request timed out")
defer cancel()
@@ -57,24 +58,30 @@ func (mon *HTTPHealthMonitor) CheckHealth() (healthy bool, detail string, err er
req.Header.Set("Connection", "close")
req.Header.Set("User-Agent", "GoDoxy/"+pkg.GetVersion())
start := time.Now()
resp, respErr := pinger.Do(req)
if respErr == nil {
resp.Body.Close()
}
result = &health.HealthCheckResult{
Latency: time.Since(start),
}
switch {
case respErr != nil:
// treat tls error as healthy
var tlsErr *tls.CertificateVerificationError
if ok := errors.As(respErr, &tlsErr); !ok {
detail = respErr.Error()
result.Detail = respErr.Error()
return
}
case resp.StatusCode == http.StatusServiceUnavailable:
detail = resp.Status
result.Detail = resp.Status
return
}
healthy = true
result.Healthy = true
return
}