Skip to content

Commit 09617ad

Browse files
henrybarretogustavosbarreto
authored andcommitted
feat(pkg): add configurable retry count on internal http client
1 parent 65582bd commit 09617ad

File tree

2 files changed

+32
-10
lines changed

2 files changed

+32
-10
lines changed

pkg/api/internalclient/client.go

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package internalclient
22

33
import (
44
"errors"
5-
"math"
65
"net"
76
"net/http"
87

@@ -20,10 +19,18 @@ type Client interface {
2019
firewallAPI
2120
}
2221

22+
// Config holds configuration options for the client.
23+
type Config struct {
24+
// RetryCount defines how many times the client should retry a request in case of failure.
25+
RetryCount int
26+
}
27+
2328
type client struct {
2429
http *resty.Client
2530
logger *logrus.Logger
2631
worker worker.Client
32+
33+
Config *Config
2734
}
2835

2936
const (
@@ -39,17 +46,14 @@ var (
3946

4047
func NewClient(opts ...clientOption) (Client, error) {
4148
httpClient := resty.New()
42-
httpClient.SetBaseURL("http://api:8080")
43-
httpClient.SetRetryCount(math.MaxInt32)
44-
httpClient.AddRetryCondition(func(r *resty.Response, err error) bool {
45-
if _, ok := err.(net.Error); ok { // if the error is a network error, retry.
46-
return true
47-
}
4849

49-
return r.StatusCode() >= http.StatusInternalServerError && r.StatusCode() != http.StatusNotImplemented
50-
})
50+
c := &client{
51+
http: httpClient,
52+
Config: &Config{
53+
RetryCount: 3,
54+
},
55+
}
5156

52-
c := &client{http: httpClient}
5357
for _, opt := range opts {
5458
if err := opt(c); err != nil {
5559
return nil, err
@@ -60,6 +64,16 @@ func NewClient(opts ...clientOption) (Client, error) {
6064
httpClient.SetLogger(&LeveledLogger{c.logger})
6165
}
6266

67+
httpClient.SetBaseURL("http://api:8080")
68+
httpClient.SetRetryCount(c.Config.RetryCount)
69+
httpClient.AddRetryCondition(func(r *resty.Response, err error) bool {
70+
if _, ok := err.(net.Error); ok { // if the error is a network error, retry.
71+
return true
72+
}
73+
74+
return r.StatusCode() >= http.StatusInternalServerError && r.StatusCode() != http.StatusNotImplemented
75+
})
76+
6377
return c, nil
6478
}
6579

pkg/api/internalclient/option.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,11 @@ func WithAsynqWorker(redisURI string) clientOption { //nolint:revive
1616
return nil
1717
}
1818
}
19+
20+
func WithConfig(cfg *Config) clientOption { //nolint:revive
21+
return func(c *client) error {
22+
c.Config = cfg
23+
24+
return nil
25+
}
26+
}

0 commit comments

Comments
 (0)