-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathevent.go
100 lines (78 loc) · 1.75 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
package cfevents
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
)
const eventUrl = "http://hottopic.apps.bogata.cf-app.com/map"
type eventHandler func(payload map[string]interface{})
type CfEvent struct {
handler eventHandler
appName string
}
func NewCfEvent(handler eventHandler) CfEvent {
appName := getAppName()
return CfEvent{
handler,
appName,
}
}
func (e *CfEvent) Run() {
http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {})
go func() {
fmt.Println("listening...")
err := http.ListenAndServe(":"+os.Getenv("PORT"), nil)
if err != nil {
panic(err)
}
}()
for {
payLoad, err := e.GetTopic()
if err != nil {
fmt.Printf("err getting from topic: %v\n", err)
} else if payLoad == nil {
fmt.Println("nothing on the topic")
} else {
e.handler(payLoad)
}
time.Sleep(3 * time.Second)
}
}
func (e *CfEvent) GetTopic() (map[string]interface{}, error) {
res, err := http.Get(fmt.Sprintf("%s/%s", eventUrl, e.appName))
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, fmt.Errorf("unexpected response while getting topic %d with body %+v", res.StatusCode, string(body))
}
var payLoad map[string]interface{}
err = json.Unmarshal(body, &payLoad)
if err != nil {
return nil, err
}
return payLoad, nil
}
func getAppName() string {
vcapApp := os.Getenv("VCAP_APPLICATION")
if vcapApp == "" {
fmt.Println("App name cannot be found in vcap")
os.Exit(1)
}
var vcap VcapApplication
err := json.Unmarshal([]byte(vcapApp), &vcap)
if err != nil {
}
return vcap.AppName
}
type VcapApplication struct {
AppName string `json:"application_name"`
}