@marcel91200 / caddy Mirror · read-only / commits / 498f32ba
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 13, 09:15 UTC

caddyconfig: Implement retries into HTTPLoader (#5077)

* httploader: Add max_retries * caddyconfig: dependency-free http config loading retries * caddyconfig: support `retry_delay` in http loader * httploader: Implement retries * Apply suggestions from code review Co-authored-by: Matt Holt <mholt@users.noreply.github.com> Co-authored-by: Matt Holt <mholt@users.noreply.github.com>

Cory Cooper committed Oct 5, 2022 at 21:34 UTC 498f32bab96ba00e1a7d04c6bc8b367c97d8a335
1 file changed +32 -1
caddyconfig/httploader.go
+32 -1
@@ -94,7 +94,7 @@ func (hl HTTPLoader) LoadConfig(ctx caddy.Context) ([]byte, error) {
94 }
95 }
96
97 - resp, err := client.Do(req)
97 + resp, err := doHttpCallWithRetries(ctx, client, req)
98 if err != nil {
99 return nil, err
100 }
@@ -119,6 +119,37 @@ func (hl HTTPLoader) LoadConfig(ctx caddy.Context) ([]byte, error) {
119 return result, nil
120 }
121
122 +func attemptHttpCall(client *http.Client, request *http.Request) (*http.Response, error) {
123 + resp, err := client.Do(request)
124 + if err != nil {
125 + return nil, fmt.Errorf("problem calling http loader url: %v", err)
126 + } else if resp.StatusCode < 200 || resp.StatusCode > 499 {
127 + return nil, fmt.Errorf("bad response status code from http loader url: %v", resp.StatusCode)
128 + }
129 + return resp, nil
130 +}
131 +
132 +func doHttpCallWithRetries(ctx caddy.Context, client *http.Client, request *http.Request) (*http.Response, error) {
133 + var resp *http.Response
134 + var err error
135 + const maxAttempts = 10
136 +
137 + // attempt up to 10 times
138 + for i := 0; i < maxAttempts; i++ {
139 + resp, err = attemptHttpCall(client, request)
140 + if err != nil && i < maxAttempts-1 {
141 + // wait 500ms before reattempting, or until context is done
142 + select {
143 + case <-time.After(time.Millisecond * 500):
144 + case <-ctx.Done():
145 + return resp, ctx.Err()
146 + }
147 + }
148 + }
149 +
150 + return resp, err
151 +}
152 +
153 func (hl HTTPLoader) makeClient(ctx caddy.Context) (*http.Client, error) {
154 client := &http.Client{
155 Timeout: time.Duration(hl.Timeout),