-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent.go
More file actions
70 lines (57 loc) · 1.71 KB
/
Copy pathevent.go
File metadata and controls
70 lines (57 loc) · 1.71 KB
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
package ship
import (
"fmt"
"reflect"
"sync"
)
// Event is a payload for a message.
type Event interface {
// EventName returns the name of the event.
EventName() string
}
var (
// eventStore is global to hold event registration data.
eventStore = make(map[string]reflect.Type)
// eventStoreMu is a mutex for locking the event store.
eventStoreMu = sync.RWMutex{}
)
// getType returns the reflected type of given value.
func getType(v interface{}) reflect.Type {
t := reflect.TypeOf(v)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t
}
// RegisterEvent registers an event to be global available for serialization, and
// other dependents. It used to create concrete event data structs when loading
// from event store.
func RegisterEvent(e Event) {
name := e.EventName()
eventStoreMu.Lock()
defer eventStoreMu.Unlock()
if _, ok := eventStore[name]; ok {
panic(fmt.Sprintf("ship: event %s is already registered", name))
}
eventStore[name] = getType(e)
}
// GetEvent returns a new instance of event matching it's name or an error if
// the event is not registered.
func GetEvent(name string) (Event, error) {
eventStoreMu.RLock()
defer eventStoreMu.RUnlock()
if eventType, ok := eventStore[name]; ok {
return reflect.New(eventType).Interface().(Event), nil
}
return nil, fmt.Errorf("ship: event %s is not registered", name)
}
// UnregisterEvent removes the event from registered events list.
// This is mainly useful in mainenance situations where the event data
// needs to be switched in a migrations or test.
func UnregisterEvent(event Event) {
name := event.EventName()
if _, ok := eventStore[name]; !ok {
panic(fmt.Sprintf("ship: event %s is not registered", name))
}
delete(eventStore, name)
}