@@ -10,6 +10,7 @@ import (
1010 "net/url"
1111 "reflect"
1212 "strings"
13+ "time"
1314 "unicode/utf8"
1415
1516 "github.com/tidepool-org/platform/errors"
@@ -35,6 +36,9 @@ type Client struct {
3536 address string
3637 userAgent string
3738 errorResponseParser ErrorResponseParser
39+
40+ // DefaultRequestTimeout applies to requests whose context doesn't include a timeout.
41+ DefaultRequestTimeout time.Duration
3842}
3943
4044func New (cfg * Config ) (* Client , error ) {
@@ -49,12 +53,15 @@ func NewWithErrorParser(cfg *Config, errorResponseParser ErrorResponseParser) (*
4953 }
5054
5155 return & Client {
52- address : cfg .Address ,
53- userAgent : cfg .UserAgent ,
54- errorResponseParser : errorResponseParser ,
56+ address : cfg .Address ,
57+ userAgent : cfg .UserAgent ,
58+ errorResponseParser : errorResponseParser ,
59+ DefaultRequestTimeout : DefaultRequestTimeout ,
5560 }, nil
5661}
5762
63+ const DefaultRequestTimeout = time .Minute
64+
5865func (c * Client ) ConstructURL (paths ... string ) string {
5966 segments := []string {}
6067 for _ , path := range paths {
@@ -92,6 +99,14 @@ func (c *Client) RequestStreamWithHTTPClient(ctx context.Context, method string,
9299 return nil , err
93100 }
94101
102+ reqCtx := req .Context ()
103+ if _ , ok := reqCtx .Deadline (); ! ok {
104+ toCtx , cancel := context .WithTimeout (reqCtx , c .DefaultRequestTimeout )
105+ defer cancel ()
106+ req = req .WithContext (toCtx )
107+ ctx = toCtx
108+ }
109+
95110 res , err := httpClient .Do (req )
96111 if err != nil {
97112 return nil , errors .Wrapf (err , "unable to perform request to %s %s" , method , url )
@@ -152,13 +167,11 @@ func (c *Client) createRequest(ctx context.Context, method string, url string, m
152167 }
153168 }
154169
155- req , err := http .NewRequest ( method , url , body )
170+ req , err := http .NewRequestWithContext ( ctx , method , url , body )
156171 if err != nil {
157172 return nil , errors .Wrapf (err , "unable to create request to %s %s" , method , url )
158173 }
159174
160- req = req .WithContext (ctx )
161-
162175 for _ , mutator := range mutators {
163176 if err = mutator .MutateRequest (req ); err != nil {
164177 return nil , errors .Wrapf (err , "unable to mutate request to %s %s" , method , url )
0 commit comments