generated from deploymenttheory/Template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jamfpro_api_request.go
96 lines (81 loc) · 2.47 KB
/
jamfpro_api_request.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// jamfpro_api_request.go
package jamfpro
import (
"bytes"
"encoding/json"
"encoding/xml"
"io"
"mime/multipart"
"path/filepath"
"strings"
"github.com/deploymenttheory/go-api-http-client/helpers"
"github.com/deploymenttheory/go-api-http-client/logger"
"go.uber.org/zap"
)
// MarshalRequest encodes the request body according to the endpoint for the API.
func (j *JamfAPIHandler) MarshalRequest(body interface{}, method string, endpoint string, log logger.Logger) ([]byte, error) {
var (
data []byte
err error
)
// Determine the format based on the endpoint
format := "json"
if strings.Contains(endpoint, "/JSSResource") {
format = "xml"
} else if strings.Contains(endpoint, "/api") {
format = "json"
}
switch format {
case "xml":
data, err = xml.Marshal(body)
if err != nil {
return nil, err
}
if method == "POST" || method == "PUT" {
j.Logger.Debug("XML Request Body", zap.String("Body", string(data)))
}
case "json":
data, err = json.Marshal(body)
if err != nil {
j.Logger.Error("Failed marshaling JSON request", zap.Error(err))
return nil, err
}
if method == "POST" || method == "PUT" || method == "PATCH" {
j.Logger.Debug("JSON Request Body", zap.String("Body", string(data)))
}
}
return data, nil
}
// MarshalMultipartRequest handles multipart form data encoding with secure file handling and returns the encoded body and content type.
func (j *JamfAPIHandler) MarshalMultipartRequest(fields map[string]string, files map[string]string, log logger.Logger) ([]byte, string, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// Add the simple fields to the form data
for field, value := range fields {
if err := writer.WriteField(field, value); err != nil {
return nil, "", err
}
}
// Add the files to the form data, using safeOpenFile to ensure secure file access
for formField, filePath := range files {
file, err := helpers.SafeOpenFile(filePath)
if err != nil {
log.Error("Failed to open file securely", zap.String("file", filePath), zap.Error(err))
return nil, "", err
}
defer file.Close()
part, err := writer.CreateFormFile(formField, filepath.Base(filePath))
if err != nil {
return nil, "", err
}
if _, err := io.Copy(part, file); err != nil {
return nil, "", err
}
}
// Close the writer to finish writing the multipart message
contentType := writer.FormDataContentType()
if err := writer.Close(); err != nil {
return nil, "", err
}
return body.Bytes(), contentType, nil
}