/
configure.go
104 lines (82 loc) · 1.57 KB
/
configure.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package x
import (
"log"
"sort"
)
type ConfigFn func(Handle) error
type Config interface {
Order() int
Configure(Handle) error
}
type config struct {
order int
fn ConfigFn
}
func DefaultConfig(fn ConfigFn) Config {
return config{50, fn}
}
func NewConfig(order int, fn ConfigFn) Config {
return config{order, fn}
}
func (c config) Order() int {
return c.order
}
func (c config) Configure(h Handle) error {
return c.fn(h)
}
type List []Config
func (l List) Len() int {
return len(l)
}
func (l List) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
func (l List) Less(i, j int) bool {
return l[i].Order() < l[j].Order()
}
type Configuration interface {
Add(...Config)
AddFn(...ConfigFn)
Configure(Handle) error
Configured() bool
}
type configuration struct {
configured bool
list List
}
func newConfiguration(conf ...Config) *configuration {
c := &configuration{
list: make([]Config, 0),
}
c.Add(conf...)
return c
}
func (c *configuration) Add(conf ...Config) {
c.list = append(c.list, conf...)
}
func (c *configuration) AddFn(fns ...ConfigFn) {
for _, fn := range fns {
c.list = append(c.list, DefaultConfig(fn))
}
}
func configure(h Handle, conf ...Config) error {
for _, c := range conf {
err := c.Configure(h)
if err != nil {
log.Printf("x:handle:configuration: %s", err.Error())
return err
}
}
return nil
}
func (c *configuration) Configure(h Handle) error {
sort.Sort(c.list)
err := configure(h, c.list...)
if err == nil {
c.configured = true
}
return err
}
func (c *configuration) Configured() bool {
return c.configured
}