Skip to content

Commit

Permalink
Merge pull request #8 from mauricioabreu/main
Browse files Browse the repository at this point in the history
Upgrade resty dependency
  • Loading branch information
Demétrio de Castro Menezes Neto authored Apr 18, 2024
2 parents dd72929 + 4f49b26 commit c32f558
Show file tree
Hide file tree
Showing 10 changed files with 91 additions and 93 deletions.
40 changes: 20 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
"context"
"log"
"time"

"github.com/globocom/httpclient"
"golang.org/x/oauth2/clientcredentials"
)
Expand All @@ -22,21 +22,21 @@ func main() {
timeout := 200 * time.Millisecond
contextTimeout, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

credentials := clientcredentials.Config{
ClientID: "client_id",
ClientSecret: "client_secret",
TokenURL: "client_url/token",
Scopes: []string{"grant_permissions:client_credentials"},
}

client := httpclient.NewHTTPClient(log.Writer(),
client := httpclient.NewHTTPClient(httpclient.LoggerAdapter{Writer: log.Writer()},
httpclient.WithOAUTHTransport(credentials, timeout))

resp, err := client.NewRequest().
SetContext(contextTimeout).
Put("/authorize")

log.Printf("resp: %#v", resp)
log.Printf("err: %s", err)
}
Expand All @@ -48,32 +48,32 @@ package example
import (
"log"
"time"

"github.com/slok/goresilience/circuitbreaker"
"github.com/globocom/httpclient"
)
func main() {
cbConfig := circuitbreaker.Config {
ErrorPercentThresholdToOpen: 5,
MinimumRequestToOpen: 50,
SuccessfulRequiredOnHalfOpen: 50,
WaitDurationInOpenState: 30 * time.Second,
MetricsSlidingWindowBucketQuantity: 5,
ErrorPercentThresholdToOpen: 5,
MinimumRequestToOpen: 50,
SuccessfulRequiredOnHalfOpen: 50,
WaitDurationInOpenState: 30 * time.Second,
MetricsSlidingWindowBucketQuantity: 5,
MetricsBucketDuration: 5 * time.Second,
}

timeout := 200 * time.Millisecond
retries := 1
backoff := 5 * time.Millisecond
maxBackoff := 10 * time.Millisecond
client := httpclient.NewHTTPClient(log.Writer(),

client := httpclient.NewHTTPClient(httpclient.LoggerAdapter{Writer: log.Writer()},
httpclient.WithDefaultTransport(timeout),
httpclient.WithTimeout(timeout),
httpclient.WithCircuitBreaker(cbConfig),
httpclient.WithRetries(retries, backoff, maxBackoff),
)

resp, err := client.NewRequest().
Get("/example")

Expand All @@ -94,7 +94,7 @@ import (

func main() {
client := httpclient.NewHTTPClient(
log.Writer(),
httpclient.LoggerAdapter{Writer: log.Writer()},
httpclient.WithChainCallback(loggerCallback),
)
resp, err := client.NewRequest().Get("example.com")
Expand All @@ -104,7 +104,7 @@ func main() {

func loggerCallback(fn func() (*httpclient.Response, error)) (*httpclient.Response, error) {
resp, err := fn()

if resp != nil {
restyRequest := resp.Request().RestyRequest()
requestURL := restyRequest.RawRequest.URL
Expand All @@ -113,12 +113,12 @@ if resp != nil {
if requestHostURL := resp.Request().HostURL(); requestHostURL != nil {
host = requestHostURL.Host
}

responseTime := resp.ResponseTime().Microseconds()
log.Printf("%s [%s] %d -- %s (%dμs)", host, restyRequest.Method,
resp.StatusCode(), requestURL.String(), responseTime)
}

return resp, err
}
```
```
8 changes: 4 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ module github.com/globocom/httpclient
go 1.18

require (
github.com/go-resty/resty/v2 v2.11.0
github.com/onsi/ginkgo v1.16.5
github.com/onsi/gomega v1.24.1
github.com/slok/goresilience v0.2.0
github.com/stretchr/testify v1.8.1
golang.org/x/oauth2 v0.2.0
gopkg.in/resty.v1 v1.12.0
)

require (
Expand All @@ -24,9 +24,9 @@ require (
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 // indirect
github.com/prometheus/common v0.0.0-20181126121408-4724e9255275 // indirect
github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a // indirect
golang.org/x/net v0.2.0 // indirect
golang.org/x/sys v0.2.0 // indirect
golang.org/x/text v0.4.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
Expand Down
76 changes: 23 additions & 53 deletions go.sum

Large diffs are not rendered by default.

14 changes: 6 additions & 8 deletions httpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,17 @@ package httpclient
import (
"context"
"crypto/tls"
"io"
"net"
"net/http"
"net/url"
"time"

resty "github.com/go-resty/resty/v2"
"github.com/slok/goresilience/circuitbreaker"
goresilienceErrors "github.com/slok/goresilience/errors"
"github.com/slok/goresilience/retry"
"golang.org/x/oauth2"
cc "golang.org/x/oauth2/clientcredentials"
resty "gopkg.in/resty.v1"
)

var ErrCircuitOpen = goresilienceErrors.ErrCircuitOpen
Expand All @@ -36,14 +35,13 @@ type (
//
// Parameters:
//
// logger: an io.Writer is used to log request and response details.
// logger: interface is used to log request and response details.
// options: specifies options to HTTPClient.
func NewHTTPClient(logger io.Writer, options ...Opt) *HTTPClient {
return newClient(resty.New().SetLogger(logger).GetClient(), false,
options...)
func NewHTTPClient(logger resty.Logger, options ...Opt) *HTTPClient {
return newClient(resty.New().SetLogger(logger).GetClient(), options...)
}

func newClient(customClient *http.Client, oauth bool, options ...Opt) *HTTPClient {
func newClient(customClient *http.Client, options ...Opt) *HTTPClient {
client := &HTTPClient{
resty: resty.NewWithClient(customClient),
callbackChain: noopCallback,
Expand Down Expand Up @@ -219,7 +217,7 @@ func WithCookie(name, value string) func(*HTTPClient) {
func WithHostURL(baseURL string) func(*HTTPClient) {
return func(client *HTTPClient) {
client.hostURL, _ = url.Parse(baseURL)
client.resty.SetHostURL(baseURL)
client.resty.SetBaseURL(baseURL)
}
}

Expand Down
8 changes: 4 additions & 4 deletions httpclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func testCircuitBreaker(t *testing.T) {
errorThreshold := 1

client := httpclient.NewHTTPClient(
io.Discard,
&httpclient.LoggerAdapter{Writer: io.Discard},
httpclient.WithDefaultTransport(1*time.Second),
httpclient.WithTimeout(1*time.Second),
httpclient.WithCircuitBreaker(circuitbreaker.Config{
Expand Down Expand Up @@ -58,14 +58,14 @@ func testRetries(t *testing.T) {
expectedTimes := 3
waitAmount := 500 * time.Millisecond
clientLinear := httpclient.NewHTTPClient(
io.Discard,
&httpclient.LoggerAdapter{Writer: io.Discard},
httpclient.WithDefaultTransport(1*time.Second),
httpclient.WithTimeout(1*time.Second),
httpclient.WithLinearBackoff(expectedTimes, waitAmount),
)

clientExponential := httpclient.NewHTTPClient(
io.Discard,
&httpclient.LoggerAdapter{Writer: io.Discard},
httpclient.WithDefaultTransport(1*time.Second),
httpclient.WithTimeout(1*time.Second),
httpclient.WithExponentialBackoff(expectedTimes, waitAmount),
Expand Down Expand Up @@ -116,7 +116,7 @@ func testCallback(t *testing.T) {
writer := io.Writer(&b)

client := httpclient.NewHTTPClient(
io.Discard,
&httpclient.LoggerAdapter{Writer: io.Discard},
httpclient.WithChainCallback(loggerCallback(writer)),
)

Expand Down
30 changes: 30 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package httpclient

import (
"fmt"
"io"
)

type LoggerAdapter struct {
Writer io.Writer
}

func (l *LoggerAdapter) Debugf(format string, v ...interface{}) {
l.logf("DEBUG: "+format, v...)
}

func (l *LoggerAdapter) Infof(format string, v ...interface{}) {
l.logf("INFO: "+format, v...)
}

func (l *LoggerAdapter) Warnf(format string, v ...interface{}) {
l.logf("WARN: "+format, v...)
}

func (l *LoggerAdapter) Errorf(format string, v ...interface{}) {
l.logf("ERROR: "+format, v...)
}

func (l *LoggerAdapter) logf(format string, v ...interface{}) {
fmt.Fprintf(l.Writer, format+"\n", v...)
}
2 changes: 1 addition & 1 deletion request.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"strings"
"time"

resty "gopkg.in/resty.v1"
resty "github.com/go-resty/resty/v2"
)

type Request struct {
Expand Down
2 changes: 1 addition & 1 deletion request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func TestRequest(t *testing.T) {
}

client := httpclient.NewHTTPClient(
io.Discard,
&httpclient.LoggerAdapter{Writer: io.Discard},
httpclient.WithHostURL(server.URL),
)

Expand Down
2 changes: 1 addition & 1 deletion response.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"net/http"
"time"

resty "gopkg.in/resty.v1"
resty "github.com/go-resty/resty/v2"
)

type Response struct {
Expand Down
2 changes: 1 addition & 1 deletion response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func TestResponse(t *testing.T) {
defer server.Close()

client := httpclient.NewHTTPClient(
io.Discard,
&httpclient.LoggerAdapter{Writer: io.Discard},
httpclient.WithHostURL(server.URL),
)

Expand Down

0 comments on commit c32f558

Please sign in to comment.