Skip to content

Commit d8a63ff

Browse files
authored
Merge pull request #66 from UpCloudLtd/client-timeout
fix(client/service): better timeout handling
2 parents 02a65fe + a9bea71 commit d8a63ff

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

upcloud/client/client.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,10 @@ func NewWithHTTPClient(userName string, password string, httpClient *http.Client
4242
client.userName = userName
4343
client.password = password
4444
client.httpClient = httpClient
45-
client.SetTimeout(time.Second * DefaultTimeout)
45+
// Set the default timeout if the caller hasn't set its own
46+
if client.httpClient.Timeout == 0 {
47+
client.SetTimeout(time.Second * DefaultTimeout)
48+
}
4649

4750
return &client
4851
}

upcloud/service/service.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -222,13 +222,20 @@ func (s *Service) StartServer(r *request.StartServerRequest) (*upcloud.ServerDet
222222

223223
// StopServer stops the specified server
224224
func (s *Service) StopServer(r *request.StopServerRequest) (*upcloud.ServerDetails, error) {
225+
// Save previous timeout
226+
prevTimeout := s.client.GetTimeout()
227+
225228
// Increase the client timeout to match the request timeout
226-
s.client.SetTimeout(r.Timeout)
229+
// Allow ten seconds to give the API a chance to respond with an error
230+
s.client.SetTimeout(r.Timeout + 10*time.Second)
227231

228232
serverDetails := upcloud.ServerDetails{}
229233
requestBody, _ := json.Marshal(r)
230234
response, err := s.client.PerformJSONPostRequest(s.client.CreateRequestURL(r.RequestURL()), requestBody)
231235

236+
// Restore previous timeout
237+
s.client.SetTimeout(prevTimeout)
238+
232239
if err != nil {
233240
return nil, parseJSONServiceError(err)
234241
}
@@ -240,13 +247,20 @@ func (s *Service) StopServer(r *request.StopServerRequest) (*upcloud.ServerDetai
240247

241248
// RestartServer restarts the specified server
242249
func (s *Service) RestartServer(r *request.RestartServerRequest) (*upcloud.ServerDetails, error) {
250+
// Save previous timeout
251+
prevTimeout := s.client.GetTimeout()
252+
243253
// Increase the client timeout to match the request timeout
244-
s.client.SetTimeout(r.Timeout)
254+
// Allow ten seconds to give the API a chance to respond with an error
255+
s.client.SetTimeout(r.Timeout + 10*time.Second)
245256

246257
serverDetails := upcloud.ServerDetails{}
247258
requestBody, _ := json.Marshal(r)
248259
response, err := s.client.PerformJSONPostRequest(s.client.CreateRequestURL(r.RequestURL()), requestBody)
249260

261+
// Restore previous timeout
262+
s.client.SetTimeout(prevTimeout)
263+
250264
if err != nil {
251265
return nil, parseJSONServiceError(err)
252266
}

0 commit comments

Comments
 (0)