transport/http: added after ClientOption to Client
Geoff Berger authored 7 years ago
Geoff Berger committed 7 years ago
17 | 17 | enc EncodeRequestFunc |
18 | 18 | dec DecodeResponseFunc |
19 | 19 | before []RequestFunc |
20 | after []ClientResponseFunc | |
20 | 21 | bufferedStream bool |
21 | 22 | } |
22 | 23 | |
35 | 36 | enc: enc, |
36 | 37 | dec: dec, |
37 | 38 | before: []RequestFunc{}, |
39 | after: []ClientResponseFunc{}, | |
38 | 40 | bufferedStream: false, |
39 | 41 | } |
40 | 42 | for _, option := range options { |
46 | 48 | // ClientOption sets an optional parameter for clients. |
47 | 49 | type ClientOption func(*Client) |
48 | 50 | |
51 | // ClientResponseFunc takes information from an HTTP request to read from the | |
52 | // response and do something additional with the response or add/update | |
53 | // context. ClientResponseFuncs are only executed on the client immediately | |
54 | // after the request has been made but prior to decoding. This allows for | |
55 | // intervention in case there is an error from the request. | |
56 | type ClientResponseFunc func(context.Context, *http.Response) | |
57 | ||
49 | 58 | // SetClient sets the underlying HTTP client used for requests. |
50 | 59 | // By default, http.DefaultClient is used. |
51 | 60 | func SetClient(client *http.Client) ClientOption { |
56 | 65 | // request before it's invoked. |
57 | 66 | func SetClientBefore(before ...RequestFunc) ClientOption { |
58 | 67 | return func(c *Client) { c.before = before } |
68 | } | |
69 | ||
70 | // SetClientAfter sets the ClientResponseFunc applied to the incoming HTTP | |
71 | // request prior to it being decoded. This is useful for obtaining anything off | |
72 | // of the response and adding onto the context prior to decoding. | |
73 | func SetClientAfter(after ...ClientResponseFunc) ClientOption { | |
74 | return func(c *Client) { c.after = after } | |
59 | 75 | } |
60 | 76 | |
61 | 77 | // SetBufferedStream sets whether the Response.Body is left open, allowing it |
84 | 100 | } |
85 | 101 | |
86 | 102 | resp, err := ctxhttp.Do(ctx, c.client, req) |
103 | for _, f := range c.after { | |
104 | f(ctx, resp) | |
105 | } | |
106 | ||
87 | 107 | if err != nil { |
88 | 108 | return nil, Error{Domain: DomainDo, Err: err} |
89 | 109 | } |