tweak(healthcheck): allow custom base context

This commit is contained in:
yusing 2025-06-04 23:14:46 +08:00
parent e82480a639
commit 45e34d691a
2 changed files with 11 additions and 3 deletions

View file

@ -1,6 +1,7 @@
package health
import (
"context"
"time"
"github.com/yusing/go-proxy/internal/common"
@ -12,6 +13,8 @@ type HealthCheckConfig struct {
UseGet bool `json:"use_get,omitempty"`
Interval time.Duration `json:"interval" validate:"omitempty,min=1s"`
Timeout time.Duration `json:"timeout" validate:"omitempty,min=1s"`
BaseContext func() context.Context `json:"-"`
}
func DefaultHealthConfig() *HealthCheckConfig {

View file

@ -87,10 +87,15 @@ func newMonitor(u *url.URL, config *health.HealthCheckConfig, healthCheckFunc He
}
func (mon *monitor) ContextWithTimeout(cause string) (ctx context.Context, cancel context.CancelFunc) {
if mon.task != nil {
return context.WithTimeoutCause(mon.task.Context(), mon.config.Timeout, errors.New(cause))
switch {
case mon.config.BaseContext != nil:
ctx = mon.config.BaseContext()
case mon.task != nil:
ctx = mon.task.Context()
default:
ctx = context.Background()
}
return context.WithTimeoutCause(context.Background(), mon.config.Timeout, errors.New(cause))
return context.WithTimeoutCause(ctx, mon.config.Timeout, errors.New(cause))
}
// Start implements task.TaskStarter.