mirror of
https://github.com/yusing/godoxy.git
synced 2026-04-21 07:51:28 +02:00
refactored some stuff, added healthcheck support, fixed 'include file' reload not showing in log
This commit is contained in:
@@ -1,67 +1,42 @@
|
||||
package loadbalancer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yusing/go-proxy/internal/net/types"
|
||||
U "github.com/yusing/go-proxy/internal/utils"
|
||||
"github.com/yusing/go-proxy/internal/watcher/health"
|
||||
)
|
||||
|
||||
type (
|
||||
Server struct {
|
||||
Name string
|
||||
URL types.URL
|
||||
Weight weightType
|
||||
handler http.Handler
|
||||
_ U.NoCopy
|
||||
|
||||
pinger *http.Client
|
||||
available atomic.Bool
|
||||
Name string
|
||||
URL types.URL
|
||||
Weight weightType
|
||||
|
||||
handler http.Handler
|
||||
healthMon health.HealthMonitor
|
||||
}
|
||||
servers []*Server
|
||||
)
|
||||
|
||||
func NewServer(name string, url types.URL, weight weightType, handler http.Handler) *Server {
|
||||
func NewServer(name string, url types.URL, weight weightType, handler http.Handler, healthMon health.HealthMonitor) *Server {
|
||||
srv := &Server{
|
||||
Name: name,
|
||||
URL: url,
|
||||
Weight: weight,
|
||||
handler: handler,
|
||||
pinger: &http.Client{Timeout: 3 * time.Second},
|
||||
Name: name,
|
||||
URL: url,
|
||||
Weight: weight,
|
||||
handler: handler,
|
||||
healthMon: healthMon,
|
||||
}
|
||||
srv.available.Store(true)
|
||||
return srv
|
||||
}
|
||||
|
||||
func (srv *Server) checkUpdateAvail(ctx context.Context) {
|
||||
req, err := http.NewRequestWithContext(
|
||||
ctx,
|
||||
http.MethodHead,
|
||||
srv.URL.String(),
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
logger.Error("failed to create request: ", err)
|
||||
srv.available.Store(false)
|
||||
}
|
||||
|
||||
resp, err := srv.pinger.Do(req)
|
||||
if err == nil && resp.StatusCode != http.StatusServiceUnavailable {
|
||||
if !srv.available.Swap(true) {
|
||||
logger.Infof("server %s is up", srv.Name)
|
||||
}
|
||||
} else if err != nil {
|
||||
if srv.available.Swap(false) {
|
||||
logger.Warnf("server %s is down: %s", srv.Name, err)
|
||||
}
|
||||
} else {
|
||||
if srv.available.Swap(false) {
|
||||
logger.Warnf("server %s is down: status %s", srv.Name, resp.Status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (srv *Server) String() string {
|
||||
return srv.Name
|
||||
}
|
||||
|
||||
func (srv *Server) IsHealthy() bool {
|
||||
return srv.healthMon.IsHealthy()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user