-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
84 lines (65 loc) · 1.53 KB
/
context.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
package gomq
import (
"context"
"fmt"
"sync"
"github.com/workspace-9/gomq/transport"
)
type Context struct {
sync.RWMutex
transports map[string]transport.Transport
ctx context.Context
}
func NewContext(ctx context.Context) *Context {
return &Context{
ctx: ctx,
transports: make(map[string]transport.Transport),
}
}
func (c *Context) getTransport(name string) (transport.Transport, bool) {
c.Lock()
defer c.Unlock()
if tp, ok := c.transports[name]; ok {
return tp, ok
}
registeredTransports.RLock()
defer registeredTransports.RUnlock()
if fac, ok := registeredTransports.transports[name]; ok {
tp := fac()
c.transports[name] = tp
return tp, true
}
return nil, false
}
func (c *Context) NewSocket(typ string, mechStr string) (*Socket, error) {
sock := &Socket{}
constructor, ok := FindSocketType(typ)
if !ok {
return nil, fmt.Errorf("%w: %s", ErrTypeNotFound, typ)
}
mechConstructor, ok := FindMechanism(mechStr)
if !ok {
return nil, fmt.Errorf("%w: %s", ErrMechanismNotFound, mechStr)
}
conf := &Config{}
conf.Default()
mech := mechConstructor()
driver, err := constructor(c.ctx, mech, conf, PrintBus{})
if err != nil {
return nil, err
}
sock.driver = driver
sock.ctx = c
sock.mech = mech
return sock, nil
}
type typeNotFound struct{}
func (typeNotFound) Error() string {
return "Type not found"
}
var ErrTypeNotFound typeNotFound
type mechanismNotFound struct{}
func (mechanismNotFound) Error() string {
return "Mechanism not found"
}
var ErrMechanismNotFound mechanismNotFound