Searchโ€ฆ
Hooks
Request events handlers
Gosip provides an events system with a set of handlers that can be optionally defined to track different client communication aspects such as request tracking, retries and response error logging, to name just a few.
To define the handlers Hooks object should be configured and passed to gosip.SPClient struct.
1
var authCnfg gosip.AuthCnfg
2
// ... auth config initiation is omitted
3
โ€‹
4
&gosip.SPClient{
5
AuthCnfg: authCnfg,
6
Hooks: &gosip.HookHandlers{
7
// handlers function definition
8
},
9
}
Copied!
The following handlers are available at the moment:
1
// HookHandlers struct to configure events handlers
2
type HookHandlers struct {
3
OnError func(event *HookEvent) // when error appeared
4
OnRetry func(event *HookEvent) // before retry request
5
OnRequest func(event *HookEvent) // before request is sent
6
OnResponse func(event *HookEvent) // after response is received
7
}
Copied!
All of the handlers are optional.
A handler receives HookEvent pointer which contains request pointer, response status code, and error (if applicable for an event), and time information to track duration since a request started an event happened.
Hooks sample:
1
// Define requests hook handlers
2
client.Hooks = &gosip.HookHandlers{
3
OnError: func(e *gosip.HookEvent) {
4
fmt.Println("\n======= On Error ========")
5
fmt.Printf(" URL: %s\n", e.Request.URL)
6
fmt.Printf(" StatusCode: %d\n", e.StatusCode)
7
fmt.Printf(" Error: %s\n", e.Error)
8
fmt.Printf(" took %f seconds\n",
9
time.Since(e.StartedAt).Seconds())
10
fmt.Printf("=========================\n\n")
11
},
12
OnRetry: func(e *gosip.HookEvent) {
13
fmt.Println("\n======= On Retry ========")
14
fmt.Printf(" URL: %s\n", e.Request.URL)
15
fmt.Printf(" StatusCode: %d\n", e.StatusCode)
16
fmt.Printf(" Error: %s\n", e.Error)
17
fmt.Printf(" took %f seconds\n",
18
time.Since(e.StartedAt).Seconds())
19
fmt.Printf("=========================\n\n")
20
},
21
OnRequest: func(e *gosip.HookEvent) {
22
if e.Error == nil {
23
fmt.Println("\n====== On Request =======")
24
fmt.Printf(" URL: %s\n", e.Request.URL)
25
fmt.Printf(" auth injection took %f seconds\n",
26
time.Since(e.StartedAt).Seconds())
27
fmt.Printf("=========================\n\n")
28
}
29
},
30
OnResponse: func(e *gosip.HookEvent) {
31
if e.Error == nil {
32
fmt.Println("\n====== On Response =======")
33
fmt.Printf(" URL: %s\n", e.Request.URL)
34
fmt.Printf(" StatusCode: %d\n", e.StatusCode)
35
fmt.Printf(" took %f seconds\n",
36
time.Since(e.StartedAt).Seconds())
37
fmt.Printf("==========================\n\n")
38
}
39
},
40
}
Copied!
Hooks can be handy for global logging streaming and metrics collection.
It is recommended using asynchronous and only lightweight logic inside hooks.
Last modified 1yr ago
Export as PDF
Copy link