-
Notifications
You must be signed in to change notification settings - Fork 43
/
event.go
107 lines (92 loc) · 2.31 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* Copyright (c) 2020 Percipia
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Contributor(s):
* Andrew Querol <aquerol@percipia.com>
*/
package eslgo
import (
"bufio"
"bytes"
"fmt"
"io"
"net/textproto"
"net/url"
"strconv"
"strings"
)
type EventListener func(event *Event)
type Event struct {
Headers textproto.MIMEHeader
Body []byte
}
const (
EventListenAll = "ALL"
)
func readPlainEvent(body []byte) (*Event, error) {
reader := bufio.NewReader(bytes.NewBuffer(body))
header := textproto.NewReader(reader)
headers, err := header.ReadMIMEHeader()
if err != nil {
return nil, err
}
event := &Event{
Headers: headers,
}
if contentLength := headers.Get("Content-Length"); len(contentLength) > 0 {
length, err := strconv.Atoi(contentLength)
if err != nil {
return event, err
}
event.Body = make([]byte, length)
_, err = io.ReadFull(reader, event.Body)
if err != nil {
return event, err
}
}
return event, nil
}
// TODO: Needs processing
func readXMLEvent(body []byte) (*Event, error) {
return &Event{
Headers: make(textproto.MIMEHeader),
}, nil
}
// TODO: Needs processing
func readJSONEvent(body []byte) (*Event, error) {
return &Event{
Headers: make(textproto.MIMEHeader),
}, nil
}
// GetName Helper function that returns the event name header
func (e Event) GetName() string {
return e.GetHeader("Event-Name")
}
// HasHeader Helper to check if the Event has a header
func (e Event) HasHeader(header string) bool {
_, ok := e.Headers[textproto.CanonicalMIMEHeaderKey(header)]
return ok
}
// GetHeader Helper function that calls e.Header.Get
func (e Event) GetHeader(header string) string {
value, _ := url.PathUnescape(e.Headers.Get(header))
return value
}
// String Implement the Stringer interface for pretty printing (%v)
func (e Event) String() string {
var builder strings.Builder
builder.WriteString(fmt.Sprintf("%s\n", e.GetName()))
for key, values := range e.Headers {
builder.WriteString(fmt.Sprintf("%s: %#v\n", key, values))
}
builder.Write(e.Body)
return builder.String()
}
// GoString Implement the GoStringer interface for pretty printing (%#v)
func (e Event) GoString() string {
return e.String()
}