-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathregistry.go
50 lines (38 loc) · 1010 Bytes
/
registry.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
package mrpc
import (
"sync"
"github.com/evergreen-ci/mrpc/mongowire"
"github.com/pkg/errors"
)
type OperationRegistry struct {
ops map[mongowire.OpScope]HandlerFunc
mu sync.RWMutex
}
func (o *OperationRegistry) Add(op mongowire.OpScope, h HandlerFunc) error {
o.mu.Lock()
defer o.mu.Unlock()
if err := op.Validate(); err != nil {
return errors.Wrap(err, "invalid operation")
}
if h == nil {
return errors.Errorf("cannot define nil handler function for operation %+v", op)
}
if _, ok := o.ops[op]; ok {
return errors.Errorf("operation '%+v' is already defined", op)
}
o.ops[op] = h
return nil
}
func (o *OperationRegistry) Get(scope *mongowire.OpScope) (HandlerFunc, bool) {
o.mu.RLock()
defer o.mu.RUnlock()
scopeCopy := *scope
if handler, ok := o.ops[scopeCopy]; ok {
return handler, ok
}
// Default to using a handler without a context if there isn't a more
// specific context match.
scopeCopy.Context = ""
handler, ok := o.ops[scopeCopy]
return handler, ok
}