Skip to content

Commit

Permalink
feat(client): add option to log requests and responses
Browse files Browse the repository at this point in the history
  • Loading branch information
kangasta committed Sep 12, 2024
1 parent a26ae13 commit e2bbe65
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 24 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,14 @@ See updating [Changelog example here](https://keepachangelog.com/en/1.0.0/)

## [Unreleased]

### Added

- client: add option to configure logger for logging requests and responses

## [8.8.0]

### Added

- managed object storage: support for custom domains
- managed load balancer: support for reading DNS challenge domain

Expand Down
101 changes: 77 additions & 24 deletions upcloud/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net"
Expand All @@ -23,11 +24,14 @@ const (
EnvDebugSkipCertificateVerify string = "UPCLOUD_DEBUG_SKIP_CERTIFICATE_VERIFY"
)

type LogFn func(context.Context, string, ...map[string]interface{})

type config struct {
username string
password string
baseURL string
httpClient *http.Client
logger LogFn
}

// Client represents an API client
Expand Down Expand Up @@ -83,13 +87,12 @@ func (c *Client) Delete(ctx context.Context, path string) ([]byte, error) {

// Do performs HTTP request and returns the response body.
func (c *Client) Do(r *http.Request) ([]byte, error) {
c.addDefaultHeaders(r)
response, err := c.config.httpClient.Do(r)
if err != nil {
return nil, err
}

return handleResponse(response)
return c.handleResponse(response)
}

func (c *Client) createRequest(ctx context.Context, method, path string, body []byte) (*http.Request, error) {
Expand All @@ -102,9 +105,35 @@ func (c *Client) createRequest(ctx context.Context, method, path string, body []
if err != nil {
return nil, err
}
c.addDefaultHeaders(req)
c.logRequest(req, body)
return req, err
}

// Parses the response and returns either the response body or an error
func (c *Client) handleResponse(response *http.Response) ([]byte, error) {
defer response.Body.Close()

// Return an error on unsuccessful requests
if response.StatusCode < 200 || response.StatusCode > 299 {
errorBody, _ := io.ReadAll(response.Body)
var errorType ErrorType
switch response.Header.Get("Content-Type") {
case "application/problem+json":
errorType = ErrorTypeProblem
default:
errorType = ErrorTypeError
}
c.logResponse(response, errorBody)
return nil, &Error{response.StatusCode, response.Status, errorBody, errorType}
}

responseBody, err := io.ReadAll(response.Body)
c.logResponse(response, responseBody)

return responseBody, err
}

func (c *Client) addDefaultHeaders(r *http.Request) {
const (
accept string = "Accept"
Expand Down Expand Up @@ -139,6 +168,45 @@ func (c *Client) getBaseURL() string {
return fmt.Sprintf("%s/%s", c.config.baseURL, APIVersion)
}

// Pretty prints given JSON bytes. If the JSON is not valid, returns the original bytes as string.
func prettyJSON(i []byte) string {
var o bytes.Buffer
if err := json.Indent(&o, i, "", " "); err != nil {
return string(i)
}
return o.String()
}

func (c *Client) logRequest(r *http.Request, body []byte) {
const authorization string = "Authorization"

if c.config.logger != nil {
headers := r.Header.Clone()
if _, ok := headers[authorization]; ok {
auth := strings.Split(headers.Get(authorization), " ")
headers.Set(authorization, fmt.Sprintf("%s xxxxx", auth[0]))
}

c.config.logger(r.Context(), "Sending request to UpCloud API", map[string]interface{}{
"url": r.URL.Redacted(),
"method": r.Method,
"headers": headers,
"body": prettyJSON(body),
})
}
}

func (c *Client) logResponse(r *http.Response, body []byte) {
if c.config.logger != nil {
c.config.logger(r.Request.Context(), "Received response from UpCloud API", map[string]interface{}{
"url": r.Request.URL.Redacted(),
"status": r.Status,
"headers": r.Header,
"body": prettyJSON(body),
})
}
}

type ConfigFn func(o *config)

// WithBaseURL modifies the client baseURL
Expand Down Expand Up @@ -181,6 +249,13 @@ func WithTimeout(timeout time.Duration) ConfigFn {
}
}

// WithLogger configures logging function that logs requests and responses
func WithLogger(logger LogFn) ConfigFn {
return func(c *config) {
c.logger = logger
}
}

// New creates and returns a new client configured with the specified user and password and optional
// config functions.
func New(username, password string, c ...ConfigFn) *Client {
Expand Down Expand Up @@ -221,28 +296,6 @@ func clientBaseURL(URL string) string {
return URL
}

// Parses the response and returns either the response body or an error
func handleResponse(response *http.Response) ([]byte, error) {
defer response.Body.Close()

// Return an error on unsuccessful requests
if response.StatusCode < 200 || response.StatusCode > 299 {
errorBody, _ := io.ReadAll(response.Body)
var errorType ErrorType
switch response.Header.Get("Content-Type") {
case "application/problem+json":
errorType = ErrorTypeProblem
default:
errorType = ErrorTypeError
}
return nil, &Error{response.StatusCode, response.Status, errorBody, errorType}
}

responseBody, err := io.ReadAll(response.Body)

return responseBody, err
}

// NewDefaultHTTPClient returns new default http.Client.
func NewDefaultHTTPClient() *http.Client {
transport := NewDefaultHTTPTransport()
Expand Down

0 comments on commit e2bbe65

Please sign in to comment.