-
Notifications
You must be signed in to change notification settings - Fork 4
/
payload.go
56 lines (43 loc) · 1.08 KB
/
payload.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
package tool
import (
"bytes"
"encoding/gob"
"sync"
)
var lock = &sync.Mutex{}
// IStructToPayloadEncoder enables struct to be payload encoder.
// Encode returns byte array, and error (which can be nil in case if there is no error)
type IStructToPayloadEncoder interface {
Encode() ([]byte, error)
SetPayload(p interface{})
}
type structToPayloadEncoder struct {
payload interface{}
buf *bytes.Buffer
}
var instance IStructToPayloadEncoder
// GetPayloadEncoder returns encoder (as singleton) which can encode given object
func GetPayloadEncoder(p interface{}) *IStructToPayloadEncoder {
if instance == nil {
// goroutine safe
lock.Lock()
defer lock.Unlock()
instance = &structToPayloadEncoder{buf: &bytes.Buffer{}}
}
instance.SetPayload(p)
return &instance
}
func (s structToPayloadEncoder) SetPayload(p interface{}) {
s.payload = p
}
func (s structToPayloadEncoder) Encode() ([]byte, error) {
if s.buf == nil {
s.buf = &bytes.Buffer{}
}
enc := gob.NewEncoder(s.buf)
err := enc.Encode(s.payload)
if err != nil {
return nil, err
}
return s.buf.Bytes(), nil
}