Skip to content

Commit ce0d676

Browse files
committed
added helpers to manage string conversion when uses time duration
1 parent 7f4e45c commit ce0d676

File tree

5 files changed

+48
-18
lines changed

5 files changed

+48
-18
lines changed

helpers/helpers.go

+23-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// helpers/helpers_test.go
1+
// helpers/helpers.go
22
package helpers
33

44
import (
@@ -54,5 +54,27 @@ func (d JSONDuration) Duration() time.Duration {
5454
return time.Duration(d)
5555
}
5656

57+
// MarshalJSON returns the JSON representation of the duration.
58+
func (d JSONDuration) String() string {
59+
return time.Duration(d).String()
60+
}
61+
5762
// JSONDuration wraps time.Duration for custom JSON unmarshalling.
5863
type JSONDuration time.Duration
64+
65+
// GetEnvOrDefault returns the value of an environment variable or a default value.
66+
func GetEnvOrDefault(envKey string, defaultValue string) string {
67+
if value, exists := os.LookupEnv(envKey); exists {
68+
return value
69+
}
70+
return defaultValue
71+
}
72+
73+
// ParseJSONDuration attempts to parse a string value as a duration and returns the result or a default value.
74+
func ParseJSONDuration(value string, defaultVal JSONDuration) JSONDuration {
75+
result, err := time.ParseDuration(value)
76+
if err != nil {
77+
return defaultVal
78+
}
79+
return JSONDuration(result)
80+
}

httpclient/client.go

+14-7
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"github.com/deploymenttheory/go-api-http-client/apiintegrations/apihandler"
1515
"github.com/deploymenttheory/go-api-http-client/authenticationhandler"
1616
"github.com/deploymenttheory/go-api-http-client/concurrency"
17+
"github.com/deploymenttheory/go-api-http-client/helpers"
1718

1819
"github.com/deploymenttheory/go-api-http-client/logger"
1920
"github.com/deploymenttheory/go-api-http-client/redirecthandler"
@@ -94,10 +95,16 @@ type ConcurrencyConfig struct {
9495
}
9596

9697
// TimeoutConfig holds custom timeout settings.
98+
// type TimeoutConfig struct {
99+
// CustomTimeout time.Duration // Custom timeout for the HTTP client
100+
// TokenRefreshBufferPeriod time.Duration // Buffer period before token expiry to attempt token refresh
101+
// TotalRetryDuration time.Duration // Total duration to attempt retries
102+
// }
103+
97104
type TimeoutConfig struct {
98-
CustomTimeout time.Duration // Custom timeout for the HTTP client
99-
TokenRefreshBufferPeriod time.Duration // Buffer period before token expiry to attempt token refresh
100-
TotalRetryDuration time.Duration // Total duration to attempt retries
105+
CustomTimeout helpers.JSONDuration // Custom timeout for the HTTP client
106+
TokenRefreshBufferPeriod helpers.JSONDuration // Buffer period before token expiry to attempt token refresh
107+
TotalRetryDuration helpers.JSONDuration // Total duration to attempt retries
101108
}
102109

103110
// RedirectConfig holds configuration related to redirect handling.
@@ -152,7 +159,7 @@ func BuildClient(config ClientConfig) (*Client, error) {
152159

153160
// Initialize the internal HTTP client
154161
httpClient := &http.Client{
155-
Timeout: config.ClientOptions.Timeout.CustomTimeout,
162+
Timeout: config.ClientOptions.Timeout.CustomTimeout.Duration(),
156163
}
157164

158165
// Conditionally setup cookie jar
@@ -206,9 +213,9 @@ func BuildClient(config ClientConfig) (*Client, error) {
206213
zap.Int("Max Concurrent Requests", config.ClientOptions.Concurrency.MaxConcurrentRequests),
207214
zap.Bool("Follow Redirects", config.ClientOptions.Redirect.FollowRedirects),
208215
zap.Int("Max Redirects", config.ClientOptions.Redirect.MaxRedirects),
209-
zap.Duration("Token Refresh Buffer Period", config.ClientOptions.Timeout.TokenRefreshBufferPeriod),
210-
zap.Duration("Total Retry Duration", config.ClientOptions.Timeout.TotalRetryDuration),
211-
zap.Duration("Custom Timeout", config.ClientOptions.Timeout.CustomTimeout),
216+
zap.Duration("Token Refresh Buffer Period", config.ClientOptions.Timeout.TokenRefreshBufferPeriod.Duration()),
217+
zap.Duration("Total Retry Duration", config.ClientOptions.Timeout.TotalRetryDuration.Duration()),
218+
zap.Duration("Custom Timeout", config.ClientOptions.Timeout.CustomTimeout.Duration()),
212219
)
213220

214221
return client, nil

httpclient/client_configuration.go

+7-6
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"strings"
1313
"time"
1414

15+
"github.com/deploymenttheory/go-api-http-client/helpers"
1516
"github.com/deploymenttheory/go-api-http-client/logger"
1617
)
1718

@@ -20,9 +21,9 @@ const (
2021
DefaultMaxRetryAttempts = 3
2122
DefaultEnableDynamicRateLimiting = true
2223
DefaultMaxConcurrentRequests = 5
23-
DefaultTokenBufferPeriod = 5 * time.Minute
24-
DefaultTotalRetryDuration = 5 * time.Minute
25-
DefaultTimeout = 10 * time.Second
24+
DefaultTokenBufferPeriod = helpers.JSONDuration(5 * time.Minute)
25+
DefaultTotalRetryDuration = helpers.JSONDuration(5 * time.Minute)
26+
DefaultTimeout = helpers.JSONDuration(10 * time.Second)
2627
FollowRedirects = true
2728
MaxRedirects = 10
2829
ConfigFileExtension = ".json"
@@ -159,13 +160,13 @@ func LoadConfigFromEnv(config *ClientConfig) (*ClientConfig, error) {
159160
log.Printf("MaxConcurrentRequests env value found and set to: %d", config.ClientOptions.Concurrency.MaxConcurrentRequests)
160161

161162
// timeouts
162-
config.ClientOptions.Timeout.TokenRefreshBufferPeriod = parseDuration(getEnvOrDefault("TOKEN_REFRESH_BUFFER_PERIOD", config.ClientOptions.Timeout.TokenRefreshBufferPeriod.String()), DefaultTokenBufferPeriod)
163+
config.ClientOptions.Timeout.TokenRefreshBufferPeriod = helpers.ParseJSONDuration(getEnvOrDefault("TOKEN_REFRESH_BUFFER_PERIOD", config.ClientOptions.Timeout.TokenRefreshBufferPeriod.String()), DefaultTokenBufferPeriod)
163164
log.Printf("TokenRefreshBufferPeriod env value found and set to: %s", config.ClientOptions.Timeout.TokenRefreshBufferPeriod)
164165

165-
config.ClientOptions.Timeout.TotalRetryDuration = parseDuration(getEnvOrDefault("TOTAL_RETRY_DURATION", config.ClientOptions.Timeout.TotalRetryDuration.String()), DefaultTotalRetryDuration)
166+
config.ClientOptions.Timeout.TotalRetryDuration = helpers.ParseJSONDuration(getEnvOrDefault("TOTAL_RETRY_DURATION", config.ClientOptions.Timeout.TotalRetryDuration.String()), DefaultTotalRetryDuration)
166167
log.Printf("TotalRetryDuration env value found and set to: %s", config.ClientOptions.Timeout.TotalRetryDuration)
167168

168-
config.ClientOptions.Timeout.CustomTimeout = parseDuration(getEnvOrDefault("CUSTOM_TIMEOUT", config.ClientOptions.Timeout.CustomTimeout.String()), DefaultTimeout)
169+
config.ClientOptions.Timeout.CustomTimeout = helpers.ParseJSONDuration(getEnvOrDefault("CUSTOM_TIMEOUT", config.ClientOptions.Timeout.CustomTimeout.String()), DefaultTimeout)
169170
log.Printf("CustomTimeout env value found and set to: %s", config.ClientOptions.Timeout.CustomTimeout)
170171

171172
// Redirects

httpclient/multipartrequest.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ func (c *Client) DoMultipartRequest(method, endpoint string, fields map[string]s
4848
ClientSecret: c.clientConfig.Auth.ClientSecret,
4949
}
5050

51-
valid, err := c.AuthTokenHandler.CheckAndRefreshAuthToken(c.APIHandler, c.httpClient, clientCredentials, c.clientConfig.ClientOptions.Timeout.TokenRefreshBufferPeriod)
51+
valid, err := c.AuthTokenHandler.CheckAndRefreshAuthToken(c.APIHandler, c.httpClient, clientCredentials, c.clientConfig.ClientOptions.Timeout.TokenRefreshBufferPeriod.Duration())
5252
if err != nil || !valid {
5353
return nil, err
5454
}

httpclient/request.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ func (c *Client) executeRequestWithRetries(method, endpoint string, body, out in
124124
ClientSecret: c.clientConfig.Auth.ClientSecret,
125125
}
126126

127-
valid, err := c.AuthTokenHandler.CheckAndRefreshAuthToken(c.APIHandler, c.httpClient, clientCredentials, c.clientConfig.ClientOptions.Timeout.TokenRefreshBufferPeriod)
127+
valid, err := c.AuthTokenHandler.CheckAndRefreshAuthToken(c.APIHandler, c.httpClient, clientCredentials, c.clientConfig.ClientOptions.Timeout.TokenRefreshBufferPeriod.Duration())
128128
if err != nil || !valid {
129129
return nil, err
130130
}
@@ -169,7 +169,7 @@ func (c *Client) executeRequestWithRetries(method, endpoint string, body, out in
169169
headerHandler.LogHeaders(c.clientConfig.ClientOptions.Logging.HideSensitiveData)
170170

171171
// Define a retry deadline based on the client's total retry duration configuration
172-
totalRetryDeadline := time.Now().Add(c.clientConfig.ClientOptions.Timeout.TotalRetryDuration)
172+
totalRetryDeadline := time.Now().Add(c.clientConfig.ClientOptions.Timeout.TotalRetryDuration.Duration())
173173

174174
var resp *http.Response
175175
var retryCount int
@@ -290,7 +290,7 @@ func (c *Client) executeRequest(method, endpoint string, body, out interface{})
290290
ClientSecret: c.clientConfig.Auth.ClientSecret,
291291
}
292292

293-
valid, err := c.AuthTokenHandler.CheckAndRefreshAuthToken(c.APIHandler, c.httpClient, clientCredentials, c.clientConfig.ClientOptions.Timeout.TokenRefreshBufferPeriod)
293+
valid, err := c.AuthTokenHandler.CheckAndRefreshAuthToken(c.APIHandler, c.httpClient, clientCredentials, c.clientConfig.ClientOptions.Timeout.TokenRefreshBufferPeriod.Duration())
294294
if err != nil || !valid {
295295
return nil, err
296296
}

0 commit comments

Comments
 (0)