feat: add cache helpers
This commit is contained in:
parent
db684e73f8
commit
3d43ff4758
8 changed files with 532 additions and 1 deletions
42
cache/retry.go
vendored
Normal file
42
cache/retry.go
vendored
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
package cache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type retry struct {
|
||||
transport http.RoundTripper
|
||||
retry int
|
||||
}
|
||||
|
||||
func (t *retry) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
var body []byte
|
||||
if req.Body != nil {
|
||||
body, _ = io.ReadAll(req.Body)
|
||||
}
|
||||
|
||||
for count := 0; count < t.retry; count++ {
|
||||
req.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
res, err := t.transport.RoundTrip(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if t.check(res) {
|
||||
if res.Body != nil {
|
||||
io.Copy(io.Discard, res.Body)
|
||||
res.Body.Close()
|
||||
}
|
||||
continue
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("too many retries")
|
||||
}
|
||||
|
||||
func (t *retry) check(res *http.Response) bool {
|
||||
return res.StatusCode > 399
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue