Skip to content

Commit

Permalink
Don't use http client timeout, use request context with timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
cudevmaxwell committed Apr 8, 2021
1 parent 8834086 commit 72b3ff9
Showing 1 changed file with 9 additions and 12 deletions.
21 changes: 9 additions & 12 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package main

import (
"bytes"
"context"
"encoding/xml"
"flag"
"fmt"
Expand Down Expand Up @@ -250,13 +251,11 @@ func SubmitJob(url *url.URL, timeout int, key string, params AlmaJob) (jobInstan
return "", err
}

// Setup an HTTP client with a timeout.
client := &http.Client{
Timeout: time.Duration(timeout) * time.Second,
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()

// Setup the request.
request, err := http.NewRequest("POST", url.String(), marshaledParams)
request, err := http.NewRequestWithContext(ctx, "POST", url.String(), marshaledParams)
if err != nil {
return "", err
}
Expand All @@ -265,7 +264,7 @@ func SubmitJob(url *url.URL, timeout int, key string, params AlmaJob) (jobInstan

// Do the request.
// On error, drain and close the response body.
resp, err := client.Do(request)
resp, err := http.DefaultClient.Do(request)
if err != nil {
if resp != nil {
_, _ = io.Copy(io.Discard, resp.Body)
Expand Down Expand Up @@ -337,21 +336,19 @@ func MonitorJobInstance(url *url.URL, timeout int, key string) (instance *AlmaJo
func GetJobInstance(url *url.URL, timeout int, key string) (instance *AlmaJobInstance, err error) {
instance = &AlmaJobInstance{}

// Setup an HTTP client with a timeout.
client := &http.Client{
Timeout: time.Duration(timeout) * time.Second,
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()

// Setup the request.
request, err := http.NewRequest("GET", url.String(), nil)
request, err := http.NewRequestWithContext(ctx, "GET", url.String(), nil)
if err != nil {
return instance, err
}
request.Header.Add("Authorization", "apikey "+key)

// Do the request.
// On error, drain and close the response body.
resp, err := client.Do(request)
resp, err := http.DefaultClient.Do(request)
if err != nil {
if resp != nil {
_, _ = io.Copy(io.Discard, resp.Body)
Expand Down

0 comments on commit 72b3ff9

Please sign in to comment.