/
broker.go
59 lines (46 loc) · 1.24 KB
/
broker.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"github.com/Sirupsen/logrus"
"github.com/go-martini/martini"
"github.com/justone/go-minibus"
)
type BrokerCommand struct {
Address string `short:"a" long:"address" description:"Address to listen on" default:":3000"`
}
var brokerCommand BrokerCommand
func (x *BrokerCommand) Execute(args []string) error {
logrus.Debugf("Running Broker")
// TODO: replace martini with a simple mux lib
m := martini.Classic()
bp := minibus.Init()
m.Get("/pmb/:bus/:agent", func(res http.ResponseWriter, params martini.Params) {
bus := params["bus"]
agent := params["agent"]
message, err := bp.Receive(bus, agent)
if err != nil {
http.Error(res, "Timeout", http.StatusRequestTimeout)
} else {
fmt.Fprintln(res, message.Contents)
}
})
m.Post("/pmb/:bus", func(res http.ResponseWriter, req *http.Request, params martini.Params) {
bus := params["bus"]
body, err := ioutil.ReadAll(req.Body)
if err != nil {
http.Error(res, "Unable to read request body: "+err.Error(), http.StatusInternalServerError)
return
}
bp.Send(bus, string(body))
})
m.RunOnAddr(brokerCommand.Address)
return nil
}
func init() {
parser.AddCommand("broker",
"Run an broker.",
"",
&brokerCommand)
}