Skip to content

Commit 190c40b

Browse files
committed
limit foreground api timeout
1 parent 9f0d741 commit 190c40b

3 files changed

Lines changed: 26 additions & 2 deletions

File tree

src/api.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,19 @@ type API struct {
1414
client *http.Client
1515
}
1616

17+
const (
18+
foregroundAPITimeout = 2 * time.Second
19+
backgroundAPITimeout = 30 * time.Second
20+
)
21+
1722
func NewAPI(cfg *Config) *API {
23+
return NewAPIWithTimeout(cfg, foregroundAPITimeout)
24+
}
25+
26+
func NewAPIWithTimeout(cfg *Config, timeout time.Duration) *API {
1827
return &API{
1928
config: cfg,
20-
client: &http.Client{Timeout: 30 * time.Second},
29+
client: &http.Client{Timeout: timeout},
2130
}
2231
}
2332

src/api_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package main
2+
3+
import (
4+
"testing"
5+
"time"
6+
)
7+
8+
func TestAPITimeouts(t *testing.T) {
9+
if got := NewAPI(&Config{}).client.Timeout; got != 2*time.Second {
10+
t.Errorf("foreground timeout = %s, want 2s", got)
11+
}
12+
if got := NewAPIWithTimeout(&Config{}, backgroundAPITimeout).client.Timeout; got != 30*time.Second {
13+
t.Errorf("background timeout = %s, want 30s", got)
14+
}
15+
}

src/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ func main() {
6363
if err != nil || config == nil {
6464
os.Exit(0)
6565
}
66-
api = NewAPI(config)
66+
api = NewAPIWithTimeout(config, backgroundAPITimeout)
6767
runContextFetchMode()
6868
os.Exit(0)
6969
}

0 commit comments

Comments
 (0)