-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
60 lines (49 loc) · 1.56 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright 2021 The httpx Authors. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package httpx
import (
"github.com/gogama/httpx/request"
)
// A HandlerGroup is a group of event handler chains which can be
// installed in a Client. Install event handlers to extend Client with
// custom functionality.
type HandlerGroup struct {
handlers [][]Handler
}
// PushBack adds an event handler to the back of the event handler chain
// for a specific event type.
func (g *HandlerGroup) PushBack(evt Event, h Handler) {
if h == nil {
panic("httpx: nil handler")
}
if g.handlers == nil {
g.handlers = make([][]Handler, numEvents)
}
g.handlers[evt] = append(g.handlers[evt], h)
}
func (g *HandlerGroup) run(evt Event, e *request.Execution) {
i := int(evt)
if i < len(g.handlers) {
run(g.handlers[i], evt, e)
}
}
func run(chain []Handler, evt Event, e *request.Execution) {
for _, h := range chain {
h.Handle(evt, e)
}
}
// A Handler handles the occurrence of an event during a request plan
// execution. Install event handlers in a Client to extend the Client
// with custom functionality.
type Handler interface {
Handle(Event, *request.Execution)
}
// The HandlerFunc type is an adapter to allow the use of ordinary
// functions as event handlers. If f is a function with appropriate
// signature, then HandlerFunc(f) is a Handler that calls f.
type HandlerFunc func(Event, *request.Execution)
// Handle calls f(evt, e).
func (f HandlerFunc) Handle(evt Event, e *request.Execution) {
f(evt, e)
}