fixes here and there

This commit is contained in:
Ben Sarmiento
2023-11-11 02:34:46 +01:00
parent 147c0bd444
commit cd96c7bd38
14 changed files with 181 additions and 155 deletions

View File

@@ -1,19 +1,32 @@
package http
import (
"io"
"net/http"
"strings"
"time"
"github.com/debridmediamanager.com/zurg/internal/config"
"github.com/debridmediamanager.com/zurg/pkg/logutil"
"go.uber.org/zap"
)
type HTTPClient struct {
Client *http.Client
MaxRetries int
Backoff func(attempt int) time.Duration
CheckRespStatus func(resp *http.Response, err error) bool
CheckRespStatus func(resp *http.Response, err error, log *zap.SugaredLogger) bool
BearerToken string
log *zap.SugaredLogger
config config.ConfigInterface
}
func (r *HTTPClient) Do(req *http.Request) (*http.Response, error) {
if r.config != nil && strings.Contains(req.Host, "download.real-debrid.") {
if host := r.config.GetRandomPreferredHost(); host != "" {
req.Host = r.config.GetRandomPreferredHost()
}
}
if r.BearerToken != "" {
req.Header.Set("Authorization", "Bearer "+r.BearerToken)
}
@@ -21,7 +34,7 @@ func (r *HTTPClient) Do(req *http.Request) (*http.Response, error) {
var err error
for attempt := 0; attempt < r.MaxRetries; attempt++ {
resp, err = r.Client.Do(req)
if !r.CheckRespStatus(resp, err) {
if !r.CheckRespStatus(resp, err, r.log) {
return resp, err
}
time.Sleep(r.Backoff(attempt))
@@ -29,7 +42,7 @@ func (r *HTTPClient) Do(req *http.Request) (*http.Response, error) {
return resp, err
}
func NewHTTPClient(token string, maxRetries int) *HTTPClient {
func NewHTTPClient(token string, maxRetries int, c config.ConfigInterface) *HTTPClient {
return &HTTPClient{
BearerToken: token,
Client: &http.Client{},
@@ -37,15 +50,21 @@ func NewHTTPClient(token string, maxRetries int) *HTTPClient {
Backoff: func(attempt int) time.Duration {
return time.Duration(attempt) * time.Second
},
CheckRespStatus: func(resp *http.Response, err error) bool {
CheckRespStatus: func(resp *http.Response, err error, log *zap.SugaredLogger) bool {
if err != nil {
return true
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := io.ReadAll(resp.Body)
body2, _ := io.ReadAll(resp.Request.Body)
log.Errorf("Received a %s %s from %s", resp.Status, string(body), resp.Request.URL)
log.Errorf("request %s %s", string(body2), resp.Request.URL)
return true
}
// no need to retry because the status code is 2XX
return false
},
log: logutil.NewLogger().Named("http"),
config: c,
}
}