Skip to content

Commit d0f2d72

Browse files
authored
Merge pull request #26 from deploymenttheory/dev
Add logger to JamfAPIHandler constructor
2 parents 4939202 + 36b9248 commit d0f2d72

File tree

2 files changed

+32
-32
lines changed

2 files changed

+32
-32
lines changed

apihandlers/jamfpro/jamfpro_api_handler.go

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ var jamfpro_api_exceptions_configuration []byte
7070

7171
// init is invoked automatically on package initialization and is responsible for
7272
// setting up the default state of the package by loading the default configuration.
73-
// If an error occurs during the loading process, the program will terminate with a fatal error log.
73+
// If an error occurs during the loading process, the program will terminate with a fatal error j.Logger.
7474
func init() {
7575
// Load the default configuration from an embedded resource.
7676
err := loadDefaultConfig()
@@ -163,15 +163,15 @@ func (j *JamfAPIHandler) SetBaseDomain() string {
163163
func (j *JamfAPIHandler) ConstructAPIResourceEndpoint(instanceName string, endpointPath string, log logger.Logger) string {
164164
urlBaseDomain := j.SetBaseDomain()
165165
url := fmt.Sprintf("https://%s%s%s", instanceName, urlBaseDomain, endpointPath)
166-
log.Info(fmt.Sprintf("Constructed %s API resource endpoint URL", APIName), zap.String("URL", url))
166+
j.Logger.Info(fmt.Sprintf("Constructed %s API resource endpoint URL", APIName), zap.String("URL", url))
167167
return url
168168
}
169169

170170
// ConstructAPIAuthEndpoint constructs the full URL for a Jamf API auth endpoint path and logs the URL.
171171
func (j *JamfAPIHandler) ConstructAPIAuthEndpoint(instanceName string, endpointPath string, log logger.Logger) string {
172172
urlBaseDomain := j.SetBaseDomain()
173173
url := fmt.Sprintf("https://%s%s%s", instanceName, urlBaseDomain, endpointPath)
174-
log.Info(fmt.Sprintf("Constructed %s API authentication URL", APIName), zap.String("URL", url))
174+
j.Logger.Info(fmt.Sprintf("Constructed %s API authentication URL", APIName), zap.String("URL", url))
175175
return url
176176
}
177177

@@ -183,36 +183,36 @@ func (j *JamfAPIHandler) ConstructAPIAuthEndpoint(instanceName string, endpointP
183183
// - For url endpoints starting with "/api", it defaults to "application/json" for the JamfPro API.
184184
// If the endpoint does not match any of the predefined patterns, "application/json" is used as a fallback.
185185
// This method logs the decision process at various stages for debugging purposes.
186-
func (u *JamfAPIHandler) GetContentTypeHeader(endpoint string, log logger.Logger) string {
186+
func (j *JamfAPIHandler) GetContentTypeHeader(endpoint string, log logger.Logger) string {
187187
// Dynamic lookup from configuration should be the first priority
188188
for key, config := range configMap {
189189
if strings.HasPrefix(endpoint, key) {
190190
if config.ContentType != nil {
191-
log.Debug("Content-Type for endpoint found in configMap", zap.String("endpoint", endpoint), zap.String("content_type", *config.ContentType))
191+
j.Logger.Debug("Content-Type for endpoint found in configMap", zap.String("endpoint", endpoint), zap.String("content_type", *config.ContentType))
192192
return *config.ContentType
193193
}
194-
log.Debug("Content-Type for endpoint is nil in configMap, handling as special case", zap.String("endpoint", endpoint))
194+
j.Logger.Debug("Content-Type for endpoint is nil in configMap, handling as special case", zap.String("endpoint", endpoint))
195195
// If a nil ContentType is an expected case, do not set Content-Type header.
196196
return "" // Return empty to indicate no Content-Type should be set.
197197
}
198198
}
199199

200200
// If no specific configuration is found, then check for standard URL patterns.
201201
if strings.Contains(endpoint, "/JSSResource") {
202-
log.Debug("Content-Type for endpoint defaulting to XML for Classic API", zap.String("endpoint", endpoint))
202+
j.Logger.Debug("Content-Type for endpoint defaulting to XML for Classic API", zap.String("endpoint", endpoint))
203203
return "application/xml" // Classic API uses XML
204204
} else if strings.Contains(endpoint, "/api") {
205-
log.Debug("Content-Type for endpoint defaulting to JSON for JamfPro API", zap.String("endpoint", endpoint))
205+
j.Logger.Debug("Content-Type for endpoint defaulting to JSON for JamfPro API", zap.String("endpoint", endpoint))
206206
return "application/json" // JamfPro API uses JSON
207207
}
208208

209209
// Fallback to JSON if no other match is found.
210-
log.Debug("Content-Type for endpoint not found in configMap or standard patterns, using default JSON", zap.String("endpoint", endpoint))
210+
j.Logger.Debug("Content-Type for endpoint not found in configMap or standard patterns, using default JSON", zap.String("endpoint", endpoint))
211211
return "application/json"
212212
}
213213

214214
// MarshalRequest encodes the request body according to the endpoint for the API.
215-
func (u *JamfAPIHandler) MarshalRequest(body interface{}, method string, endpoint string, log logger.Logger) ([]byte, error) {
215+
func (j *JamfAPIHandler) MarshalRequest(body interface{}, method string, endpoint string, log logger.Logger) ([]byte, error) {
216216
var (
217217
data []byte
218218
err error
@@ -234,54 +234,54 @@ func (u *JamfAPIHandler) MarshalRequest(body interface{}, method string, endpoin
234234
}
235235

236236
if method == "POST" || method == "PUT" {
237-
log.Debug("XML Request Body", zap.String("Body", string(data)))
237+
j.Logger.Debug("XML Request Body", zap.String("Body", string(data)))
238238
}
239239

240240
case "json":
241241
data, err = json.Marshal(body)
242242
if err != nil {
243-
log.Error("Failed marshaling JSON request", zap.Error(err))
243+
j.Logger.Error("Failed marshaling JSON request", zap.Error(err))
244244
return nil, err
245245
}
246246

247247
if method == "POST" || method == "PUT" || method == "PATCH" {
248-
log.Debug("JSON Request Body", zap.String("Body", string(data)))
248+
j.Logger.Debug("JSON Request Body", zap.String("Body", string(data)))
249249
}
250250
}
251251

252252
return data, nil
253253
}
254254

255255
// UnmarshalResponse decodes the response body from XML or JSON format depending on the Content-Type header.
256-
func (u *JamfAPIHandler) UnmarshalResponse(resp *http.Response, out interface{}, log logger.Logger) error {
256+
func (j *JamfAPIHandler) UnmarshalResponse(resp *http.Response, out interface{}, log logger.Logger) error {
257257
// Handle DELETE method
258258
if resp.Request.Method == "DELETE" {
259259
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
260260
return nil
261261
} else {
262-
return log.Error("DELETE request failed", zap.Int("Status Code", resp.StatusCode))
262+
return j.Logger.Error("DELETE request failed", zap.Int("Status Code", resp.StatusCode))
263263
}
264264
}
265265

266266
bodyBytes, err := io.ReadAll(resp.Body)
267267
if err != nil {
268-
log.Error("Failed reading response body", zap.Error(err))
268+
j.Logger.Error("Failed reading response body", zap.Error(err))
269269
return err
270270
}
271271

272272
// Log the raw response body and headers
273-
log.Debug("Raw HTTP Response", zap.String("Body", string(bodyBytes)))
274-
log.Debug("Unmarshaling response", zap.String("status", resp.Status))
273+
j.Logger.Debug("Raw HTTP Response", zap.String("Body", string(bodyBytes)))
274+
j.Logger.Debug("Unmarshaling response", zap.String("status", resp.Status))
275275

276276
// Log headers when in debug mode
277-
log.Debug("HTTP Response Headers", zap.Any("Headers", resp.Header))
277+
j.Logger.Debug("HTTP Response Headers", zap.Any("Headers", resp.Header))
278278

279279
// Check the Content-Type and Content-Disposition headers
280280
contentType := resp.Header.Get("Content-Type")
281281
contentDisposition := resp.Header.Get("Content-Disposition")
282282

283283
// Handle binary data if necessary
284-
if err := u.handleBinaryData(contentType, contentDisposition, bodyBytes, out); err != nil {
284+
if err := j.handleBinaryData(contentType, contentDisposition, bodyBytes, out); err != nil {
285285
return err
286286
}
287287

@@ -292,13 +292,13 @@ func (u *JamfAPIHandler) UnmarshalResponse(resp *http.Response, out interface{},
292292
htmlErrorMessage := ExtractErrorMessageFromHTML(string(bodyBytes))
293293

294294
// Log the HTML error message using Zap
295-
log.Error("Received HTML error content",
295+
j.Logger.Error("Received HTML error content",
296296
zap.String("error_message", htmlErrorMessage),
297297
zap.Int("status_code", resp.StatusCode),
298298
)
299299
} else {
300300
// Log a generic error message if the response is not HTML
301-
log.Error("Received non-success status code without detailed error response",
301+
j.Logger.Error("Received non-success status code without detailed error response",
302302
zap.Int("status_code", resp.StatusCode),
303303
)
304304
}
@@ -311,22 +311,22 @@ func (u *JamfAPIHandler) UnmarshalResponse(resp *http.Response, out interface{},
311311
description, err := ParseJSONErrorResponse(bodyBytes)
312312
if err != nil {
313313
// Log the error using the structured logger and return the error
314-
log.Error("Failed to parse JSON error response",
314+
j.Logger.Error("Failed to parse JSON error response",
315315
zap.Error(err),
316316
zap.Int("status_code", resp.StatusCode),
317317
)
318318
return err
319319
}
320320
// Log the error with description using the structured logger and return the error
321-
log.Error("Received non-success status code with JSON response",
321+
j.Logger.Error("Received non-success status code with JSON response",
322322
zap.Int("status_code", resp.StatusCode),
323323
zap.String("error_description", description),
324324
)
325325
return fmt.Errorf("received non-success status code with JSON response: %s", description)
326326
}
327327

328328
// If the response is not JSON or another error occurs, log a generic error message and return an error
329-
log.Error("Received non-success status code without JSON response",
329+
j.Logger.Error("Received non-success status code without JSON response",
330330
zap.Int("status_code", resp.StatusCode),
331331
)
332332
return fmt.Errorf("received non-success status code without JSON response: %d", resp.StatusCode)
@@ -350,19 +350,19 @@ func (u *JamfAPIHandler) UnmarshalResponse(resp *http.Response, out interface{},
350350
htmlErrorMessage := ExtractErrorMessageFromHTML(string(bodyBytes))
351351

352352
// Log the HTML error message
353-
log.Warn("Received HTML content instead of expected format",
353+
j.Logger.Warn("Received HTML content instead of expected format",
354354
zap.String("error_message", htmlErrorMessage),
355355
zap.Int("status_code", resp.StatusCode),
356356
)
357357

358358
// Use the HTML error message for logging the error
359-
log.Error("Unmarshal error with HTML content",
359+
j.Logger.Error("Unmarshal error with HTML content",
360360
zap.String("error_message", htmlErrorMessage),
361361
zap.Int("status_code", resp.StatusCode),
362362
)
363363
} else {
364364
// If the error is not due to HTML content, log the original error
365-
log.Error("Unmarshal error",
365+
j.Logger.Error("Unmarshal error",
366366
zap.Error(err),
367367
zap.Int("status_code", resp.StatusCode),
368368
)
@@ -379,7 +379,7 @@ func (u *JamfAPIHandler) UnmarshalResponse(resp *http.Response, out interface{},
379379
// the server is informed of the client's versatile content handling capabilities while
380380
// indicating a preference for XML. The specified MIME types cover common content formats like
381381
// images, JSON, XML, HTML, plain text, and certificates, with a fallback option for all other types.
382-
func (u *JamfAPIHandler) GetAcceptHeader() string {
382+
func (j *JamfAPIHandler) GetAcceptHeader() string {
383383
weightedAcceptHeader := "application/x-x509-ca-cert;q=0.95," +
384384
"application/pkix-cert;q=0.94," +
385385
"application/pem-certificate-chain;q=0.93," +
@@ -399,7 +399,7 @@ func (u *JamfAPIHandler) GetAcceptHeader() string {
399399
}
400400

401401
// MarshalMultipartFormData takes a map with form fields and file paths and returns the encoded body and content type.
402-
func (u *JamfAPIHandler) MarshalMultipartRequest(fields map[string]string, files map[string]string, log logger.Logger) ([]byte, string, error) {
402+
func (j *JamfAPIHandler) MarshalMultipartRequest(fields map[string]string, files map[string]string, log logger.Logger) ([]byte, string, error) {
403403
body := &bytes.Buffer{}
404404
writer := multipart.NewWriter(body)
405405

@@ -437,7 +437,7 @@ func (u *JamfAPIHandler) MarshalMultipartRequest(fields map[string]string, files
437437
}
438438

439439
// handleBinaryData checks if the response should be treated as binary data and assigns to out if so.
440-
func (u *JamfAPIHandler) handleBinaryData(contentType, contentDisposition string, bodyBytes []byte, out interface{}) error {
440+
func (j *JamfAPIHandler) handleBinaryData(contentType, contentDisposition string, bodyBytes []byte, out interface{}) error {
441441
if strings.Contains(contentType, "application/octet-stream") || strings.HasPrefix(contentDisposition, "attachment") {
442442
if outPointer, ok := out.(*[]byte); ok {
443443
*outPointer = bodyBytes

httpclient/httpclient_api_handler.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ func LoadAPIHandler(apiType string, log logger.Logger) (APIHandler, error) {
3636
switch apiType {
3737
case "jamfpro":
3838
apiHandler = &jamfpro.JamfAPIHandler{
39-
39+
Logger: log,
4040
// Initialize with necessary parameters
4141
}
4242
log.Info("API handler loaded successfully", zap.String("APIType", apiType))

0 commit comments

Comments
 (0)