-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.go
More file actions
108 lines (89 loc) · 2.6 KB
/
main.go
File metadata and controls
108 lines (89 loc) · 2.6 KB
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
108
package main
import (
"encoding/json"
"fmt"
"github.com/streadway/amqp"
"github.com/tkanos/gonfig"
"log"
"net/http"
"ttnmapper-ingress-api/types"
"ttnmapper-ingress-api/utils"
)
import "github.com/go-chi/chi"
var publishChannel = make(chan types.TtnMapperUplinkMessage, 100)
type Configuration struct {
AmqpHost string `env:"AMQP_HOST"`
AmqpPort string `env:"AMQP_PORT"`
AmqpUser string `env:"AMQP_USER"`
AmqpPassword string `env:"AMQP_PASSWORD"`
HttpListenAddress string `env:"HTTP_LISTEN_ADDRESS"`
}
var myConfiguration = Configuration{
AmqpHost: "localhost",
AmqpPort: "5672",
AmqpUser: "guest",
AmqpPassword: "guest",
HttpListenAddress: ":8080",
}
func main() {
err := gonfig.GetConf("conf.json", &myConfiguration)
if err != nil {
fmt.Println(err)
}
log.Printf("[Configuration]\n%s\n", utils.PrettyPrint(myConfiguration)) // output: [UserA, UserB]
router := Routes(publishChannel)
log.Print("[Routes]")
walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
log.Printf("%s %s\n", method, route)
return nil
}
if err := chi.Walk(router, walkFunc); err != nil {
log.Panicf("Logging err: %s\n", err.Error())
}
// Start the thread that process the queue
go publishFromChannel()
// Start the http endpoint
log.Fatal(http.ListenAndServe(myConfiguration.HttpListenAddress, router))
}
func publishFromChannel() {
conn, err := amqp.Dial("amqp://" + myConfiguration.AmqpUser + ":" + myConfiguration.AmqpPassword + "@" + myConfiguration.AmqpHost + ":" + myConfiguration.AmqpPort + "/")
//if err != nil {
// log.Print("Error connecting to RabbitMQ")
// return
//}
utils.FailOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()
ch, err := conn.Channel()
utils.FailOnError(err, "Failed to open a channel")
defer ch.Close()
err = ch.ExchangeDeclare(
"new_packets", // name
"fanout", // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // arguments
)
//var message map[string]interface{}
for {
message := <-publishChannel
log.Printf("Publishing message")
data, err := json.Marshal(message)
if err != nil {
fmt.Printf("marshal failed: %s", err)
continue
}
err = ch.Publish(
"new_packets", // exchange
"", // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
DeliveryMode: amqp.Persistent,
ContentType: "text/plain",
Body: []byte(data),
})
utils.FailOnError(err, "Failed to publish a message")
}
}