-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
97 lines (81 loc) · 2.32 KB
/
utils.go
File metadata and controls
97 lines (81 loc) · 2.32 KB
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
97
package cumi
import (
"net/url"
"strings"
)
// defaultResultChecker checks the state of the response based on status code
func defaultResultChecker(resp *Response) ResultState {
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return SuccessState
}
if resp.StatusCode >= 400 {
return ErrorState
}
return UnknownState
}
// buildURL builds the final URL with base URL, path params, and query params
func (c *Client) buildURL(rawURL string, pathParams map[string]string, queryParams url.Values) (*url.URL, error) {
finalURL := rawURL
// Add base URL if relative
if !strings.HasPrefix(rawURL, "http") && c.baseURL != "" {
finalURL = c.baseURL + "/" + strings.TrimLeft(rawURL, "/")
}
// Replace path parameters
allPathParams := make(map[string]string)
for k, v := range c.pathParams {
allPathParams[k] = v
}
for k, v := range pathParams {
allPathParams[k] = v
}
for key, value := range allPathParams {
placeholder := "{" + key + "}"
finalURL = strings.ReplaceAll(finalURL, placeholder, value)
}
u, err := url.Parse(finalURL)
if err != nil {
return nil, err
}
// Merge query parameters
q := u.Query()
for k, values := range c.queryParams {
for _, v := range values {
q.Add(k, v)
}
}
for k, values := range queryParams {
for _, v := range values {
q.Add(k, v)
}
}
u.RawQuery = q.Encode()
return u, nil
}
// shouldRetry determines if a request should be retried based on response and error
func (c *Client) shouldRetry(resp *Response, err error) bool {
if c.retryCondition != nil {
return c.retryCondition(resp, err)
}
// Default retry logic
if err != nil {
return true // Retry on network errors
}
if resp != nil && (resp.StatusCode >= 500 || resp.StatusCode == 429) {
return true // Retry on server errors and rate limiting
}
return false
}
// unmarshalResponse unmarshals the response body into the given interface
func (c *Client) unmarshalResponse(resp *Response, v interface{}) error {
if len(resp.body) == 0 {
return nil
}
contentType := resp.Header.Get("Content-Type")
if strings.Contains(contentType, "application/json") {
return c.jsonUnmarshal(resp.body, v)
} else if strings.Contains(contentType, "application/xml") || strings.Contains(contentType, "text/xml") {
return c.xmlUnmarshal(resp.body, v)
}
// Default to JSON
return c.jsonUnmarshal(resp.body, v)
}