-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp-to-rabbit.go
103 lines (79 loc) · 1.83 KB
/
http-to-rabbit.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
package main
import (
"io/ioutil"
"log"
"net/http"
"strconv"
logger "github.com/sirupsen/logrus"
application "gepur.com/http-to-rabbit/application"
)
type Message struct {
queueName string
body string
errorChanel chan<- PublishResult
}
type PublishResult struct {
success bool
error string
}
func main() {
config, err := configuration()
if err != nil {
log.Printf("%s: %s", "Configuration fail", err)
return
}
initLogger(config)
manager := createPublishManger(config)
messageChanel := make(chan Message)
defer close(messageChanel)
logger.Info("Service strated")
// register publisher worker
go func(messages <-chan Message) {
for {
msg := <-messages
err = manager.publishWithReconnects(msg.queueName, msg.body)
var res PublishResult
if err != nil {
res = PublishResult{
success: false,
error: err.Error(),
}
} else {
res = PublishResult{
success: true,
error: "",
}
}
msg.errorChanel <- res
}
}(messageChanel)
app := &application.App{
DefaultRoute: func(resp application.Response, req application.Request) {
resp.Text(http.StatusNotFound, "Not found")
},
}
app.Handle(`^/([\w\._-]+)$`, func(resp application.Response, req application.Request) {
queueName := req.Params[0]
b, err := ioutil.ReadAll(req.Body)
defer req.Body.Close()
if err != nil {
http.Error(resp, err.Error(), http.StatusBadRequest)
return
}
respChan := make(chan PublishResult)
defer close(respChan)
messageChanel <- Message{
queueName: queueName,
body: string(b),
errorChanel: respChan,
}
PublishResult := <-respChan
if !PublishResult.success {
resp.Error(PublishResult.error)
return
}
resp.Success()
})
portString := strconv.Itoa(config.ListenPort)
logger.Fatal(http.ListenAndServe(":"+portString, app))
}