refactor(http): implement shared transport and clients (#1288)

* fix(http): flip to a shared transport and clients

* nice threads

* that is terrible

* fake uri for magnet

* lazy locking

* why bother with r's

* flip magic params to struct

* refactor(http-clients): use separate clients with shared transport

* refactor(http-clients): add missing license header

* refactor(http-clients): defer and fix errors

---------

Co-authored-by: ze0s <ze0s@riseup.net>
This commit is contained in:
Kyle Sanderson 2023-12-29 14:49:22 -08:00 committed by GitHub
parent 2a4fb7750b
commit 3234f0d919
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
48 changed files with 537 additions and 391 deletions

View file

@ -71,14 +71,14 @@ func (c *client) post(ctx context.Context, endpoint string, data interface{}) (*
res, err := c.http.Do(req)
if err != nil {
return nil, errors.Wrap(err, "could not make request: %+v", req)
return res, errors.Wrap(err, "could not make request: %+v", req)
}
// validate response
if res.StatusCode == http.StatusUnauthorized {
return nil, errors.New("unauthorized: bad credentials")
return res, errors.New("unauthorized: bad credentials")
} else if res.StatusCode != http.StatusOK {
return nil, errors.New("sonarr: bad request")
return res, errors.New("sonarr: bad request")
}
// return raw response and let the caller handle json unmarshal of body

View file

@ -15,6 +15,7 @@ import (
"log"
"github.com/autobrr/autobrr/pkg/errors"
"github.com/autobrr/autobrr/pkg/sharedhttp"
)
type Config struct {
@ -43,20 +44,19 @@ type client struct {
// New create new sonarr client
func New(config Config) Client {
httpClient := &http.Client{
Timeout: time.Second * 120,
Timeout: time.Second * 120,
Transport: sharedhttp.Transport,
}
c := &client{
config: config,
http: httpClient,
Log: config.Log,
Log: log.New(io.Discard, "", log.LstdFlags),
}
if config.Log == nil {
// if no provided logger then use io.Discard
c.Log = log.New(io.Discard, "", log.LstdFlags)
if config.Log != nil {
c.Log = config.Log
}
return c

View file

@ -1,26 +1,27 @@
// Copyright (c) 2021 - 2023, Ludvig Lundgren and the autobrr contributors.
// SPDX-License-Identifier: GPL-2.0-or-later
//go:build integration
package sonarr
import (
"context"
"io/ioutil"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/rs/zerolog"
"github.com/stretchr/testify/assert"
)
func Test_client_Push(t *testing.T) {
// disable logger
zerolog.SetGlobalLevel(zerolog.Disabled)
log.SetOutput(ioutil.Discard)
log.SetOutput(io.Discard)
mux := http.NewServeMux()
ts := httptest.NewServer(mux)
@ -125,7 +126,7 @@ func Test_client_Push(t *testing.T) {
func Test_client_Test(t *testing.T) {
// disable logger
zerolog.SetGlobalLevel(zerolog.Disabled)
log.SetOutput(ioutil.Discard)
log.SetOutput(io.Discard)
key := "mock-key"