-
Notifications
You must be signed in to change notification settings - Fork 24
/
injector_slow.go
67 lines (55 loc) · 1.53 KB
/
injector_slow.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
61
62
63
64
65
66
67
package fault
import (
"net/http"
"reflect"
"time"
)
// SlowInjector waits and then continues the request.
type SlowInjector struct {
duration time.Duration
slowF func(t time.Duration)
reporter Reporter
}
// SlowInjectorOption configures a SlowInjector.
type SlowInjectorOption interface {
applySlowInjector(i *SlowInjector) error
}
type slowFunctionOption func(t time.Duration)
func (o slowFunctionOption) applySlowInjector(i *SlowInjector) error {
i.slowF = o
return nil
}
// WithSlowFunc sets the function that will be used to wait the time.Duration.
func WithSlowFunc(f func(t time.Duration)) SlowInjectorOption {
return slowFunctionOption(f)
}
func (o reporterOption) applySlowInjector(i *SlowInjector) error {
i.reporter = o.reporter
return nil
}
// NewSlowInjector returns a SlowInjector.
func NewSlowInjector(d time.Duration, opts ...SlowInjectorOption) (*SlowInjector, error) {
// set defaults
si := &SlowInjector{
duration: d,
slowF: time.Sleep,
reporter: NewNoopReporter(),
}
// apply options
for _, opt := range opts {
err := opt.applySlowInjector(si)
if err != nil {
return nil, err
}
}
return si, nil
}
// Handler runs i.slowF to wait the set duration and then continues.
func (i *SlowInjector) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
go i.reporter.Report(reflect.ValueOf(*i).Type().Name(), StateStarted)
i.slowF(i.duration)
go i.reporter.Report(reflect.ValueOf(*i).Type().Name(), StateFinished)
next.ServeHTTP(w, r)
})
}