Skip to content

Commit 003b713

Browse files
committed
Refactor API handler and module name***
1 parent 382cd64 commit 003b713

File tree

5 files changed

+33
-211
lines changed

5 files changed

+33
-211
lines changed

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
module github.com/deploymenttheory/go-api-sdk-jamfpro
1+
module github.com/deploymenttheory/go-api-http-client
22

33
go 1.21
44

internal/apihandlers/graph/graph_api_handler.go

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ import (
3737
"strings"
3838

3939
_ "embed"
40+
41+
"github.com/deploymenttheory/go-api-http-client/internal/httpclient"
4042
)
4143

4244
// Endpoint constants represent the URL suffixes used for Graph API token interactions.
@@ -107,32 +109,20 @@ type EndpointConfig struct {
107109
// This handler is responsible for encoding and decoding request and response data,
108110
// determining content types, and other API interactions as defined by the APIHandler interface.
109111
type GraphAPIHandler struct {
110-
logger Logger // logger is used to output logs for the API handling processes.
112+
logger httpclient.Logger // logger is used to output logs for the API handling processes.
111113
endpointAcceptedFormatsCache map[string][]string
112114
}
113115

114116
// Functions
115117

116118
// ConstructMSGraphAPIEndpoint constructs the full URL for an MS Graph API endpoint.
117119
// The function takes version (e.g., "/v1.0" or "/beta") and the specific API path.
118-
func (c *Client) ConstructMSGraphAPIEndpoint(endpointPath string) string {
120+
func (g *GraphAPIHandler) ConstructMSGraphAPIEndpoint(endpointPath string) string {
119121
url := fmt.Sprintf("https://%s%s", DefaultBaseDomain, endpointPath)
120-
c.logger.Info("Request will be made to MS Graph API URL:", "URL", url)
122+
g.logger.Info("Request will be made to MS Graph API URL:", "URL", url)
121123
return url
122124
}
123125

124-
// APIHandler is an interface for encoding, decoding, and determining content types for different API implementations.
125-
// It encapsulates behavior for encoding and decoding requests and responses.
126-
type APIHandler interface {
127-
MarshalRequest(body interface{}, method string, endpoint string) ([]byte, error)
128-
MarshalMultipartRequest(fields map[string]string, files map[string]string) ([]byte, string, error) // New method for multipart
129-
UnmarshalResponse(resp *http.Response, out interface{}) error
130-
GetContentTypeHeader(method string) string
131-
GetAcceptHeader() string
132-
SetLogger(logger Logger)
133-
FetchSupportedRequestFormats(endpoint string) ([]string, error)
134-
}
135-
136126
// GetAPIHandler initializes and returns an APIHandler with a configured logger.
137127
func GetAPIHandler(config Config) APIHandler {
138128
handler := &GraphAPIHandler{}

internal/apihandlers/jamfpro/jamfpro_api_handler.go

Lines changed: 17 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ import (
4848
"strings"
4949

5050
_ "embed"
51+
52+
"github.com/deploymenttheory/go-api-http-client/internal/httpclient"
5153
)
5254

5355
// Endpoint constants represent the URL suffixes used for Jamf API token interactions.
@@ -93,92 +95,47 @@ func loadDefaultConfig() error {
9395
return json.Unmarshal(jamfpro_api_exceptions_configuration, &configMap)
9496
}
9597

96-
// LoadUserConfig allows users to apply their own configuration by providing a JSON file.
97-
// The custom configuration will override the default settings previously loaded.
98-
// It reads the file from the provided filename path and unmarshals its content into the configMap.
99-
// If reading or unmarshalling fails, an error is returned.
100-
func LoadUserConfig(filename string) error {
101-
// Read the user-provided JSON configuration file and unmarshal it into the global configMap.
102-
userConfigBytes, err := os.ReadFile(filename)
103-
if err != nil {
104-
return err
105-
}
106-
// Override the default configuration with the user's custom settings.
107-
return json.Unmarshal(userConfigBytes, &configMap)
108-
}
109-
110-
// Structs
111-
11298
// EndpointConfig is a struct that holds configuration details for a specific API endpoint.
11399
// It includes what type of content it can accept and what content type it should send.
114100
type EndpointConfig struct {
115101
Accept string `json:"accept"` // Accept specifies the MIME type the endpoint can handle in responses.
116102
ContentType *string `json:"content_type"` // ContentType, if not nil, specifies the MIME type to set for requests sent to the endpoint. A pointer is used to distinguish between a missing field and an empty string.
117103
}
118104

119-
// UnifiedAPIHandler is a struct that implements the APIHandler interface.
120-
// It holds a Logger instance to facilitate logging across various API handling methods.
121-
// This handler is responsible for encoding and decoding request and response data,
122-
// determining content types, and other API interactions as defined by the APIHandler interface.
105+
// JamfAPIHandler implements the APIHandler interface for the Jamf Pro API.
123106
type JamfAPIHandler struct {
124-
logger Logger // logger is used to output logs for the API handling processes.
107+
logger httpclient.Logger // logger is used to output logs for the API handling processes.
108+
OverrideBaseDomain string // OverrideBaseDomain is used to override the base domain for URL construction.
109+
InstanceName string // InstanceName is the name of the Jamf instance.
125110
}
126111

127112
// Functions
128113

129114
// GetBaseDomain returns the appropriate base domain for URL construction.
130115
// It uses OverrideBaseDomain if set, otherwise falls back to DefaultBaseDomain.
131-
func (c *Client) GetBaseDomain() string {
132-
if c.OverrideBaseDomain != "" {
133-
return c.OverrideBaseDomain
116+
func (j *JamfAPIHandler) GetBaseDomain() string {
117+
if j.OverrideBaseDomain != "" {
118+
return j.OverrideBaseDomain
134119
}
135120
return DefaultBaseDomain
136121
}
137122

138123
// ConstructAPIResourceEndpoint returns the full URL for a Jamf API resource endpoint path.
139-
func (c *Client) ConstructAPIResourceEndpoint(endpointPath string) string {
140-
baseDomain := c.GetBaseDomain()
141-
url := fmt.Sprintf("https://%s%s%s", c.InstanceName, baseDomain, endpointPath)
142-
c.logger.Info("Request will be made to API URL:", "URL", url)
124+
func (j *JamfAPIHandler) ConstructAPIResourceEndpoint(endpointPath string) string {
125+
baseDomain := j.GetBaseDomain()
126+
url := fmt.Sprintf("https://%s%s%s", j.InstanceName, baseDomain, endpointPath)
127+
j.logger.Info("Request will be made to API URL:", "URL", url)
143128
return url
144129
}
145130

146131
// ConstructAPIAuthEndpoint returns the full URL for a Jamf API auth endpoint path.
147-
func (c *Client) ConstructAPIAuthEndpoint(endpointPath string) string {
148-
baseDomain := c.GetBaseDomain()
149-
url := fmt.Sprintf("https://%s%s%s", c.InstanceName, baseDomain, endpointPath)
150-
c.logger.Info("Request will be made to API authentication URL:", "URL", url)
132+
func (j *JamfAPIHandler) ConstructAPIAuthEndpoint(endpointPath string) string {
133+
baseDomain := j.GetBaseDomain()
134+
url := fmt.Sprintf("https://%s%s%s", j.InstanceName, baseDomain, endpointPath)
135+
j.logger.Info("Request will be made to API authentication URL:", "URL", url)
151136
return url
152137
}
153138

154-
/*
155-
// APIHandler is an interface for encoding, decoding, and determining content types for different API implementations.
156-
// It encapsulates behavior for encoding and decoding requests and responses.
157-
type APIHandler interface {
158-
MarshalRequest(body interface{}, method string, endpoint string) ([]byte, error)
159-
MarshalMultipartRequest(fields map[string]string, files map[string]string) ([]byte, string, error) // New method for multipart
160-
UnmarshalResponse(resp *http.Response, out interface{}) error
161-
GetContentTypeHeader(method string) string
162-
GetAcceptHeader() string
163-
SetLogger(logger Logger)
164-
}
165-
*/
166-
// GetAPIHandler initializes and returns an APIHandler with a configured logger.
167-
func GetAPIHandler(config Config) APIHandler {
168-
handler := &JamfAPIHandler{}
169-
logger := NewDefaultLogger()
170-
logger.SetLevel(config.LogLevel) // Use the LogLevel from the config
171-
handler.SetLogger(logger)
172-
return handler
173-
}
174-
175-
// SetLogger assigns a Logger instance to the UnifiedAPIHandler.
176-
// This allows for logging throughout the handler's operations,
177-
// enabling consistent logging that follows the configuration of the provided Logger.
178-
func (u *JamfAPIHandler) SetLogger(logger Logger) {
179-
u.logger = logger
180-
}
181-
182139
// GetContentTypeHeader determines the appropriate Content-Type header for a given API endpoint.
183140
// It attempts to find a content type that matches the endpoint prefix in the global configMap.
184141
// If a match is found and the content type is defined (not nil), it returns the specified content type.

internal/httpclient/api_handler.go

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
1-
// http_client_auth_token_management.go
1+
// api_handler.go
22
package httpclient
33

44
import (
55
"fmt"
66
"net/http"
77

8-
"github.com/deploymenttheory/go-api-sdk-jamfpro/internal/apihandlers/graph"
9-
"github.com/deploymenttheory/go-api-sdk-jamfpro/internal/apihandlers/jamfpro"
8+
"github.com/deploymenttheory/go-api-http-client/internal/apihandlers/jamfpro"
109
)
1110

1211
// APIHandler is an interface for encoding, decoding, and determining content types for different API implementations.
1312
// It encapsulates behavior for encoding and decoding requests and responses.
1413
type APIHandler interface {
14+
GetBaseDomain() string
15+
ConstructAPIResourceEndpoint(endpointPath string) string
16+
ConstructAPIAuthEndpoint(endpointPath string) string
1517
MarshalRequest(body interface{}, method string, endpoint string) ([]byte, error)
1618
MarshalMultipartRequest(fields map[string]string, files map[string]string) ([]byte, string, error) // New method for multipart
1719
UnmarshalResponse(resp *http.Response, out interface{}) error
@@ -29,11 +31,11 @@ func LoadAPIHandler(config Config, apiType string) (APIHandler, error) {
2931
apiHandler = &jamfpro.JamfAPIHandler{
3032
// Initialize with necessary parameters
3133
}
32-
case "graph":
33-
// Assuming GetAPIHandler returns a GraphAPIHandler
34-
apiHandler = &graph.GraphAPIHandler{
35-
// Initialize with necessary parameters
36-
}
34+
/*case "graph":
35+
// Assuming GetAPIHandler returns a GraphAPIHandler
36+
apiHandler = &graph.GraphAPIHandler{
37+
// Initialize with necessary parameters
38+
}*/
3739
default:
3840
return nil, fmt.Errorf("unsupported API type: %s", apiType)
3941
}

internal/httpclient/http_client_oauth.go

Lines changed: 0 additions & 127 deletions
Original file line numberDiff line numberDiff line change
@@ -100,133 +100,6 @@ func (c *Client) ObtainOAuthToken(credentials AuthConfig) error {
100100
return nil
101101
}
102102

103-
/*
104-
// ObtainOAuthToken fetches an OAuth access token using the provided OAuthCredentials (Client ID and Client Secret).
105-
// It updates the client's Token and Expiry fields with the obtained values.
106-
func (c *Client) ObtainOAuthToken(credentials AuthConfig) error {
107-
authenticationEndpoint := c.ConstructAPIAuthEndpoint(OAuthTokenEndpoint)
108-
data := url.Values{}
109-
data.Set("client_id", credentials.ClientID)
110-
data.Set("client_secret", credentials.ClientSecret)
111-
data.Set("grant_type", "client_credentials")
112-
113-
req, err := http.NewRequest("POST", authenticationEndpoint, strings.NewReader(data.Encode()))
114-
if err != nil {
115-
return err
116-
}
117-
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
118-
119-
resp, err := c.httpClient.Do(req)
120-
if err != nil {
121-
return err
122-
}
123-
defer resp.Body.Close()
124-
125-
// Debug: Print the entire raw response body for inspection
126-
127-
bodyBytes, _ := io.ReadAll(resp.Body)
128-
129-
// Reset the response body to its original state
130-
resp.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
131-
132-
oauthResp := &OAuthResponse{}
133-
err = json.NewDecoder(resp.Body).Decode(oauthResp)
134-
if err != nil {
135-
return err
136-
}
137-
138-
if oauthResp.Error != "" { // Check if the "error" field is non-empty
139-
return fmt.Errorf("error obtaining OAuth token: %s", oauthResp.Error)
140-
}
141-
142-
if oauthResp.AccessToken == "" {
143-
return fmt.Errorf("empty access token received")
144-
}
145-
146-
// Calculate and format token expiration time
147-
expiresIn := time.Duration(oauthResp.ExpiresIn) * time.Second
148-
expirationTime := time.Now().Add(expiresIn)
149-
formattedExpirationTime := expirationTime.Format(time.RFC1123) // or any other preferred format
150-
151-
// Log the token life expiry details in a human-readable format
152-
c.logger.Debug("The OAuth token obtained is: ",
153-
"Valid for", expiresIn.String(),
154-
"Expires at", formattedExpirationTime)
155-
156-
c.Token = oauthResp.AccessToken
157-
c.Expiry = time.Now().Add(time.Second * time.Duration(oauthResp.ExpiresIn))
158-
159-
return nil
160-
}
161-
*/
162-
163-
// RefreshOAuthToken refreshes the current OAuth token.
164-
// func (c *Client) RefreshOAuthToken() error {
165-
// c.tokenLock.Lock()
166-
// defer c.tokenLock.Unlock()
167-
168-
// tokenRefreshEndpoint := c.ConstructAPIAuthEndpoint(OAuthTokenEndpoint)
169-
170-
// req, err := http.NewRequest("POST", tokenRefreshEndpoint, nil)
171-
// if err != nil {
172-
// c.logger.Error("Failed to create new request for OAuth token refresh", "error", err)
173-
// return err
174-
// }
175-
// req.Header.Add("Authorization", "Bearer "+c.Token)
176-
177-
// c.logger.Debug("Attempting to refresh OAuth token", "URL", tokenRefreshEndpoint)
178-
179-
// resp, err := c.httpClient.Do(req)
180-
// if err != nil {
181-
// c.logger.Error("Failed to make request for OAuth token refresh", "error", err)
182-
// return err
183-
// }
184-
// defer resp.Body.Close()
185-
186-
// if resp.StatusCode != http.StatusOK {
187-
// c.logger.Warn("OAuth token refresh response status is not OK", "StatusCode", resp.StatusCode)
188-
// return c.HandleAPIError(resp)
189-
// }
190-
191-
// tokenResp := &TokenResponse{}
192-
// err = json.NewDecoder(resp.Body).Decode(tokenResp)
193-
// if err != nil {
194-
// c.logger.Error("Failed to decode OAuth token response", "error", err)
195-
// return err
196-
// }
197-
198-
// c.logger.Debug("OAuth token refreshed successfully", "Expiry", tokenResp.Expires)
199-
200-
// c.Token = tokenResp.Token
201-
// c.Expiry = tokenResp.Expires
202-
// return nil
203-
// }
204-
205-
/*
206-
// InvalidateOAuthToken invalidates the current OAuth access token.
207-
// After invalidation, the token cannot be used for further API requests.
208-
func (c *Client) InvalidateOAuthToken() error {
209-
invalidateTokenEndpoint := c.ConstructAPIAuthEndpoint(TokenInvalidateEndpoint)
210-
req, err := http.NewRequest("POST", invalidateTokenEndpoint, nil)
211-
if err != nil {
212-
return err
213-
}
214-
req.Header.Add("Authorization", "Bearer "+c.Token)
215-
216-
resp, err := c.httpClient.Do(req)
217-
if err != nil {
218-
return err
219-
}
220-
defer resp.Body.Close()
221-
222-
if resp.StatusCode != http.StatusNoContent {
223-
return fmt.Errorf("failed to invalidate token, status code: %d", resp.StatusCode)
224-
}
225-
226-
return nil
227-
}
228-
*/
229-
230103
// InvalidateOAuthToken invalidates the current OAuth access token.
231104
// After invalidation, the token cannot be used for further API requests.
232105
func (c *Client) InvalidateOAuthToken() error {

0 commit comments

Comments
 (0)