This repository has been archived by the owner on Jan 13, 2023. It is now read-only.
/
event.go
76 lines (59 loc) 路 1.73 KB
/
event.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
package data
import (
"encoding/hex"
"encoding/json"
"fmt"
"log"
"strings"
"github.com/lib/pq"
)
// Event - Single event entity holder, extracted from db
type Event struct {
Origin string `gorm:"column:origin"`
Index uint `gorm:"column:index"`
Topics pq.StringArray `gorm:"column:topics;type:text[]"`
Data []byte `gorm:"column:data"`
TransactionHash string `gorm:"column:txhash"`
BlockHash string `gorm:"column:blockhash"`
}
// MarshalBinary - Implementing binary marshalling function, to be invoked
// by redis before publishing data on channel
func (e *Event) MarshalBinary() ([]byte, error) {
return e.MarshalJSON()
}
// MarshalJSON - Custom JSON encoder
func (e *Event) MarshalJSON() ([]byte, error) {
data := ""
if _h := hex.EncodeToString(e.Data); _h != "" && _h != strings.Repeat("0", 64) {
data = fmt.Sprintf("0x%s", _h)
}
return []byte(fmt.Sprintf(`{"origin":%q,"index":%d,"topics":%v,"data":%q,"txHash":%q,"blockHash":%q}`,
e.Origin,
e.Index,
strings.Join(
strings.Fields(
fmt.Sprintf("%q", e.Topics)), ","),
data, e.TransactionHash, e.BlockHash)), nil
}
// ToJSON - Encoding into JSON
func (e *Event) ToJSON() []byte {
data, err := json.Marshal(e)
if err != nil {
log.Printf("[!] Failed to encode event to JSON : %s\n", err.Error())
return nil
}
return data
}
// Events - A collection of event holder, to be delivered to client in this form
type Events struct {
Events []*Event `json:"events"`
}
// ToJSON - Encoding to JSON
func (e *Events) ToJSON() []byte {
data, err := json.Marshal(e)
if err != nil {
log.Printf("[!] Failed to encode events to JSON : %s\n", err.Error())
return nil
}
return data
}