|
95 | 95 | // SuccessHook type is for reacting to request success |
96 | 96 | SuccessHook func(*Client, *Response) |
97 | 97 |
|
| 98 | + // CloseHook type is for reacting to client closing |
| 99 | + CloseHook func() |
| 100 | + |
98 | 101 | // RequestFunc type is for extended manipulation of the Request instance |
99 | 102 | RequestFunc func(*Request) *Request |
100 | 103 |
|
@@ -215,6 +218,7 @@ type Client struct { |
215 | 218 | invalidHooks []ErrorHook |
216 | 219 | panicHooks []ErrorHook |
217 | 220 | successHooks []SuccessHook |
| 221 | + closeHooks []CloseHook |
218 | 222 | contentTypeEncoders map[string]ContentTypeEncoder |
219 | 223 | contentTypeDecoders map[string]ContentTypeDecoder |
220 | 224 | contentDecompresserKeys []string |
@@ -838,6 +842,15 @@ func (c *Client) OnPanic(h ErrorHook) *Client { |
838 | 842 | return c |
839 | 843 | } |
840 | 844 |
|
| 845 | +// OnClose method adds a callback that will be run whenever the client is closed. |
| 846 | +// The hooks are executed in the order they were registered. |
| 847 | +func (c *Client) OnClose(h CloseHook) *Client { |
| 848 | + c.lock.Lock() |
| 849 | + defer c.lock.Unlock() |
| 850 | + c.closeHooks = append(c.closeHooks, h) |
| 851 | + return c |
| 852 | +} |
| 853 | + |
841 | 854 | // ContentTypeEncoders method returns all the registered content type encoders. |
842 | 855 | func (c *Client) ContentTypeEncoders() map[string]ContentTypeEncoder { |
843 | 856 | c.lock.RLock() |
@@ -2221,10 +2234,14 @@ func (c *Client) Clone(ctx context.Context) *Client { |
2221 | 2234 |
|
2222 | 2235 | // Close method performs cleanup and closure activities on the client instance |
2223 | 2236 | func (c *Client) Close() error { |
| 2237 | + // Execute close hooks first |
| 2238 | + c.onCloseHooks() |
| 2239 | + |
2224 | 2240 | if c.LoadBalancer() != nil { |
2225 | 2241 | silently(c.LoadBalancer().Close()) |
2226 | 2242 | } |
2227 | 2243 | close(c.certWatcherStopChan) |
| 2244 | + |
2228 | 2245 | return nil |
2229 | 2246 | } |
2230 | 2247 |
|
@@ -2381,6 +2398,15 @@ func (c *Client) onInvalidHooks(req *Request, err error) { |
2381 | 2398 | } |
2382 | 2399 | } |
2383 | 2400 |
|
| 2401 | +// Helper to run closeHooks hooks. |
| 2402 | +func (c *Client) onCloseHooks() { |
| 2403 | + c.lock.RLock() |
| 2404 | + defer c.lock.RUnlock() |
| 2405 | + for _, h := range c.closeHooks { |
| 2406 | + h() |
| 2407 | + } |
| 2408 | +} |
| 2409 | + |
2384 | 2410 | func (c *Client) debugf(format string, v ...any) { |
2385 | 2411 | if c.IsDebug() { |
2386 | 2412 | c.Logger().Debugf(format, v...) |
|
0 commit comments