Skip to content

Commit 487b529

Browse files
committed
Add deprecation header check and logging
1 parent 11ad03f commit 487b529

File tree

2 files changed

+36
-34
lines changed

2 files changed

+36
-34
lines changed

internal/httpclient/http_helpers.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"strings"
1010
"time"
1111

12+
"github.com/deploymenttheory/go-api-http-client/internal/logger"
1213
"go.uber.org/zap"
1314
)
1415

@@ -26,12 +27,11 @@ func EnsureHTTPScheme(url string) string {
2627
}
2728

2829
// CheckDeprecationHeader checks the response headers for the Deprecation header and logs a warning if present.
29-
func CheckDeprecationHeader(resp *http.Response, logger Logger) {
30+
func CheckDeprecationHeader(resp *http.Response, log logger.Logger) {
3031
deprecationHeader := resp.Header.Get("Deprecation")
3132
if deprecationHeader != "" {
32-
// logger is an instance of defaultLogger that wraps a *zap.Logger
33-
zapLogger := logger.(*defaultLogger).logger // Type assertion to access the underlying *zap.Logger
34-
zapLogger.Warn("API endpoint is deprecated",
33+
34+
log.Warn("API endpoint is deprecated",
3535
zap.String("Date", deprecationHeader),
3636
zap.String("Endpoint", resp.Request.URL.String()),
3737
)

internal/httpclient/http_request.go

Lines changed: 32 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import (
77
"fmt"
88
"net/http"
99
"time"
10+
11+
"github.com/deploymenttheory/go-api-http-client/internal/logger"
1012
)
1113

1214
// DoRequest constructs and executes a standard HTTP request with support for retry logic.
@@ -40,9 +42,9 @@ import (
4042
// Note:
4143
// The function assumes that retryable HTTP methods have been properly defined in the retryableHTTPMethods map.
4244
// It is the caller's responsibility to close the response body when the request is successful to avoid resource leaks.
43-
func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*http.Response, error) {
45+
func (c *Client) DoRequest(method, endpoint string, body, out interface{}, log logger.Logger) (*http.Response, error) {
4446
// Auth Token validation check
45-
valid, err := c.ValidAuthTokenCheck()
47+
valid, err := c.ValidAuthTokenCheck(log)
4648
if err != nil || !valid {
4749
return nil, fmt.Errorf("validity of the authentication token failed with error: %w", err)
4850
}
@@ -70,7 +72,7 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
7072
apiHandler := c.APIHandler
7173

7274
// Marshal Request with correct encoding
73-
requestData, err := apiHandler.MarshalRequest(body, method, endpoint, c.logger)
75+
requestData, err := apiHandler.MarshalRequest(body, method, endpoint, log)
7476
if err != nil {
7577
return nil, err
7678
}
@@ -90,9 +92,9 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
9092
}
9193

9294
// Define header content type based on url and http method
93-
contentType := apiHandler.GetContentTypeHeader(endpoint, c.logger)
95+
contentType := apiHandler.GetContentTypeHeader(endpoint, log)
9496
// Define Request Headers dynamically based on handler logic
95-
acceptHeader := apiHandler.GetAcceptHeader(c.logger)
97+
acceptHeader := apiHandler.GetAcceptHeader()
9698

9799
// Set Headers
98100
req.Header.Add("Authorization", "Bearer "+c.Token)
@@ -101,7 +103,7 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
101103
req.Header.Set("User-Agent", GetUserAgentHeader())
102104

103105
// Debug: Print request headers if in debug mode
104-
c.logger.Debug("HTTP Request Headers:", req.Header)
106+
log.Debug("HTTP Request Headers:", req.Header)
105107

106108
// Define if request is retryable
107109
retryableHTTPMethods := map[string]bool{
@@ -131,7 +133,7 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
131133
// Execute the request
132134
resp, err := c.httpClient.Do(req)
133135
if err != nil {
134-
c.logger.Error("Failed to send multipart request",
136+
log.Error("Failed to send multipart request",
135137
"method", method,
136138
"endpoint", endpoint,
137139
"error", err.Error(),
@@ -146,15 +148,15 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
146148

147149
// Checks for the presence of a deprecation header in the HTTP response and logs if found.
148150
if i == 0 {
149-
CheckDeprecationHeader(resp, c.logger)
151+
CheckDeprecationHeader(resp, log)
150152
}
151153

152154
// Handle (unmarshal) response with API Handler
153-
if err := apiHandler.UnmarshalResponse(resp, out, c.logger); err != nil {
155+
if err := apiHandler.UnmarshalResponse(resp, out, log); err != nil {
154156
switch e := err.(type) {
155157
case *APIError: // Assuming APIError is a type that includes StatusCode and Message
156158
// Log the API error with structured logging
157-
c.logger.Error("Received an API error",
159+
log.Error("Received an API error",
158160
"method", method,
159161
"endpoint", endpoint,
160162
"status_code", e.StatusCode,
@@ -163,7 +165,7 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
163165
return resp, e
164166
default:
165167
// Log the default error with structured logging
166-
c.logger.Error("Failed to unmarshal HTTP response",
168+
log.Error("Failed to unmarshal HTTP response",
167169
"method", method,
168170
"endpoint", endpoint,
169171
"error", err.Error(), // Convert error to string to log as a value
@@ -174,15 +176,15 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
174176

175177
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
176178
// Log successful HTTP request
177-
c.logger.Info("HTTP request succeeded",
179+
log.Info("HTTP request succeeded",
178180
"method", method,
179181
"endpoint", endpoint,
180182
"status_code", resp.StatusCode,
181183
)
182184
return resp, nil
183185
} else if resp.StatusCode == http.StatusNotFound {
184186
// Log when resource is not found
185-
c.logger.Warn("Resource not found",
187+
log.Warn("Resource not found",
186188
"method", method,
187189
"endpoint", endpoint,
188190
"status_code", resp.StatusCode,
@@ -192,7 +194,7 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
192194

193195
// Retry Logic
194196
if IsNonRetryableError(resp) {
195-
c.logger.Warn("Encountered a non-retryable error",
197+
log.Warn("Encountered a non-retryable error",
196198
"method", method,
197199
"endpoint", endpoint,
198200
"status_code", resp.StatusCode,
@@ -201,7 +203,7 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
201203
return resp, c.HandleAPIError(resp)
202204
} else if IsRateLimitError(resp) {
203205
waitDuration := parseRateLimitHeaders(resp) // Parses headers to determine wait duration
204-
c.logger.Warn("Encountered a rate limit error. Retrying after wait duration.",
206+
log.Warn("Encountered a rate limit error. Retrying after wait duration.",
205207
"method", method,
206208
"endpoint", endpoint,
207209
"status_code", resp.StatusCode,
@@ -212,7 +214,7 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
212214
continue // This will restart the loop, effectively "retrying" the request
213215
} else if IsTransientError(resp) {
214216
waitDuration := calculateBackoff(i) // Calculates backoff duration
215-
c.logger.Warn("Encountered a transient error. Retrying after backoff.",
217+
log.Warn("Encountered a transient error. Retrying after backoff.",
216218
"method", method,
217219
"endpoint", endpoint,
218220
"status_code", resp.StatusCode,
@@ -223,7 +225,7 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
223225
i++
224226
continue // This will restart the loop, effectively "retrying" the request
225227
} else {
226-
c.logger.Error("Received unexpected error status from HTTP request",
228+
log.Error("Received unexpected error status from HTTP request",
227229
"method", method,
228230
"endpoint", endpoint,
229231
"status_code", resp.StatusCode,
@@ -240,7 +242,7 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
240242
// Execute the request
241243
resp, err := c.httpClient.Do(req)
242244
if err != nil {
243-
c.logger.Error("Failed to send multipart request",
245+
log.Error("Failed to send multipart request",
244246
"method", method,
245247
"endpoint", endpoint,
246248
"error", err.Error(),
@@ -254,14 +256,14 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
254256
c.PerfMetrics.TotalResponseTime += responseDuration
255257
c.PerfMetrics.lock.Unlock()
256258

257-
CheckDeprecationHeader(resp, c.logger)
259+
CheckDeprecationHeader(resp, log)
258260

259261
// Handle (unmarshal) response with API Handler
260-
if err := apiHandler.UnmarshalResponse(resp, out, c.logger); err != nil {
262+
if err := apiHandler.UnmarshalResponse(resp, out, log); err != nil {
261263
switch e := err.(type) {
262264
case *APIError: // Assuming APIError is a type that includes StatusCode and Message
263265
// Log the API error with structured logging
264-
c.logger.Error("Received an API error",
266+
log.Error("Received an API error",
265267
"method", method,
266268
"endpoint", endpoint,
267269
"status_code", e.StatusCode,
@@ -270,7 +272,7 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
270272
return resp, e
271273
default:
272274
// Log the default error with structured logging
273-
c.logger.Error("Failed to unmarshal HTTP response",
275+
log.Error("Failed to unmarshal HTTP response",
274276
"method", method,
275277
"endpoint", endpoint,
276278
"error", err.Error(), // Convert error to string to log as a value
@@ -288,7 +290,7 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
288290
statusDescription := TranslateStatusCode(resp.StatusCode)
289291

290292
// Log the error with structured context
291-
c.logger.Error("Received non-success status code from HTTP request",
293+
log.Error("Received non-success status code from HTTP request",
292294
"method", method,
293295
"endpoint", endpoint,
294296
"status_code", resp.StatusCode,
@@ -340,7 +342,7 @@ func (c *Client) DoMultipartRequest(method, endpoint string, fields map[string]s
340342
apiHandler := c.APIHandler
341343

342344
// Marshal the multipart form data
343-
requestData, contentType, err := apiHandler.MarshalMultipartRequest(fields, files, c.logger)
345+
requestData, contentType, err := apiHandler.MarshalMultipartRequest(fields, files, log)
344346
if err != nil {
345347
return nil, err
346348
}
@@ -362,15 +364,15 @@ func (c *Client) DoMultipartRequest(method, endpoint string, fields map[string]s
362364
// Debug: Print request headers if in debug mode
363365

364366
// Check if logging level is DEBUG or higher before logging headers
365-
if c.logger.GetLogLevel() <= LogLevelDebug {
367+
if log.GetLogLevel() <= LogLevelDebug {
366368
// Debug: Print request headers without hiding sensitive information
367-
LogHTTPHeaders(c.logger, req.Header, false) // Use false to display all headers
369+
LogHTTPHeaders(log, req.Header, false) // Use false to display all headers
368370
}
369371

370372
// Execute the request
371373
resp, err := c.httpClient.Do(req)
372374
if err != nil {
373-
c.logger.Error("Failed to send multipart request",
375+
log.Error("Failed to send multipart request",
374376
"method", method,
375377
"endpoint", endpoint,
376378
"error", err.Error(),
@@ -380,7 +382,7 @@ func (c *Client) DoMultipartRequest(method, endpoint string, fields map[string]s
380382

381383
// Check for successful status code
382384
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
383-
c.logger.Error("Received non-success status code from multipart request",
385+
log.Error("Received non-success status code from multipart request",
384386
"method", method,
385387
"endpoint", endpoint,
386388
"status_code", resp.StatusCode,
@@ -390,8 +392,8 @@ func (c *Client) DoMultipartRequest(method, endpoint string, fields map[string]s
390392
}
391393

392394
// Unmarshal the response
393-
if err := apiHandler.UnmarshalResponse(resp, out, c.logger); err != nil {
394-
c.logger.Error("Failed to unmarshal HTTP response",
395+
if err := apiHandler.UnmarshalResponse(resp, out, log); err != nil {
396+
log.Error("Failed to unmarshal HTTP response",
395397
"method", method,
396398
"endpoint", endpoint,
397399
"error", err.Error(),

0 commit comments

Comments
 (0)