/
http.go
99 lines (83 loc) · 2.06 KB
/
http.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
package pmb
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/Sirupsen/logrus"
)
func connectHTTP(URI string, id string, sub string) (*Connection, error) {
in := make(chan Message, 10)
out := make(chan Message, 10)
done := make(chan error)
var finalURI string
if len(sub) > 0 {
finalURI = fmt.Sprintf("%s-%s", URI, sub)
} else {
finalURI = URI
}
conn := &Connection{In: in, Out: out, uri: finalURI, prefix: "", Id: id}
logrus.Debugf("calling listen/send HTTP")
go listenToHTTP(conn, done, id)
go sendToHTTP(conn, done, id)
for i := 1; i <= 2; i++ {
err := <-done
if err != nil {
return nil, err
}
}
return conn, nil
return nil, nil
}
func listenToHTTP(pmbConn *Connection, done chan error, id string) {
listenURI := fmt.Sprintf("%s/%s", pmbConn.uri, id)
logrus.Debugf("Listening on URI %s.", listenURI)
done <- nil
for {
res, err := http.Get(listenURI)
if err != nil {
logrus.Warningf("Error receiving: %s", err)
time.Sleep(1 * time.Second)
continue
}
body, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
logrus.Warningf("Error reading body: %s", err)
time.Sleep(1 * time.Second)
continue
}
if res.StatusCode == 200 {
parseMessage(body, pmbConn.Keys, pmbConn.In, id)
} else if res.StatusCode == 408 {
continue
} else {
logrus.Warningf("Bad request: %s", res.Status)
time.Sleep(1 * time.Second)
}
}
}
func sendToHTTP(pmbConn *Connection, done chan error, id string) {
logrus.Debugf("Sending to URI %s.", pmbConn.uri)
done <- nil
for {
message := <-pmbConn.Out
bodies, err := prepareMessage(message, pmbConn.Keys, id)
if err != nil {
logrus.Warningf("Error preparing message: %s", err)
continue
}
for _, body := range bodies {
logrus.Debugf("Sending raw message: %s", string(body))
_, err := http.Post(pmbConn.uri, "application/json", bytes.NewReader(body))
if err != nil {
logrus.Warningf("Error sending: %s", err)
}
}
if message.Done != nil {
logrus.Debugf("Done channel present, sending message")
message.Done <- nil
}
}
}