This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
92 lines (84 loc) · 1.85 KB
/
server.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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"miauw.social/auth/config"
"os"
"time"
amqp "github.com/rabbitmq/amqp091-go"
"gorm.io/gorm"
"miauw.social/auth/database"
"miauw.social/auth/handlers"
)
func Serve(queueName string, handler func(*gorm.DB, []byte) (handlers.Response, error)) {
cfg := config.GetConfig()
conn, err := amqp.Dial(cfg.RabbitMQ)
failOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()
ch, err := conn.Channel()
failOnError(err, "Failed to open channel.")
defer ch.Close()
q, err := ch.QueueDeclare(
queueName,
true,
false,
false,
false,
nil,
)
failOnError(err, "Failed to declare queue.")
messages, err := ch.Consume(
q.Name,
"consumerTag",
false,
false,
false,
false,
nil,
)
failOnError(err, "Failed to register a consumer.")
var forever chan struct{}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
for d := range messages {
start := time.Now()
r, err := handler(database.Conn(), d.Body)
took := time.Since(start).Milliseconds()
if err != nil {
return
}
if d.ReplyTo != "" {
jsonResponse, _ := json.Marshal(r)
headers := make(map[string]interface{})
headers["X-Process-Time"] = took
hostname, _ := os.Hostname()
headers["X-Worker"] = hostname
err := ch.PublishWithContext(ctx,
"",
d.ReplyTo,
false,
false,
amqp.Publishing{
Headers: headers,
ContentType: "application/json",
CorrelationId: d.CorrelationId,
Body: []byte(jsonResponse),
})
if err != nil {
fmt.Printf("Error: %v", err)
}
}
d.Ack(true)
}
}()
log.Printf(" [*] Waiting for %s. To exit press Ctrl-C.", queueName)
<-forever
}
func failOnError(err error, msg string) {
if err != nil {
log.Panicf(" [!] %s: %s", err, msg)
}
}