From 190c40b49648cd14370a4d964f47a874a6bc23a7 Mon Sep 17 00:00:00 2001 From: Jacques Verre Date: Fri, 12 Jun 2026 13:21:57 +0100 Subject: [PATCH] limit foreground api timeout --- src/api.go | 11 ++++++++++- src/api_test.go | 15 +++++++++++++++ src/main.go | 2 +- 3 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 src/api_test.go diff --git a/src/api.go b/src/api.go index 0c6309c..77bb68a 100644 --- a/src/api.go +++ b/src/api.go @@ -14,10 +14,19 @@ type API struct { client *http.Client } +const ( + foregroundAPITimeout = 2 * time.Second + backgroundAPITimeout = 30 * time.Second +) + func NewAPI(cfg *Config) *API { + return NewAPIWithTimeout(cfg, foregroundAPITimeout) +} + +func NewAPIWithTimeout(cfg *Config, timeout time.Duration) *API { return &API{ config: cfg, - client: &http.Client{Timeout: 30 * time.Second}, + client: &http.Client{Timeout: timeout}, } } diff --git a/src/api_test.go b/src/api_test.go new file mode 100644 index 0000000..e9f9dd2 --- /dev/null +++ b/src/api_test.go @@ -0,0 +1,15 @@ +package main + +import ( + "testing" + "time" +) + +func TestAPITimeouts(t *testing.T) { + if got := NewAPI(&Config{}).client.Timeout; got != 2*time.Second { + t.Errorf("foreground timeout = %s, want 2s", got) + } + if got := NewAPIWithTimeout(&Config{}, backgroundAPITimeout).client.Timeout; got != 30*time.Second { + t.Errorf("background timeout = %s, want 30s", got) + } +} diff --git a/src/main.go b/src/main.go index ce65fac..2820193 100644 --- a/src/main.go +++ b/src/main.go @@ -63,7 +63,7 @@ func main() { if err != nil || config == nil { os.Exit(0) } - api = NewAPI(config) + api = NewAPIWithTimeout(config, backgroundAPITimeout) runContextFetchMode() os.Exit(0) }