/
simulator.go
103 lines (79 loc) · 1.71 KB
/
simulator.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 (
"bufio"
"encoding/json"
"fmt"
"log"
"os"
"simulator/entity"
"simulator/queue"
"strings"
"time"
"github.com/joho/godotenv"
"github.com/streadway/amqp"
)
var active []string
func init() {
err := godotenv.Load()
if err != nil {
panic("Error loading .env file")
}
}
func main() {
in := make(chan []byte)
ch := queue.Connect()
queue.StartConsuming(in, ch)
for msg := range in {
var order entity.Order
err := json.Unmarshal(msg, &order)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println("New order Received: ", order.Uuid)
start(order, ch)
}
}
func start(order entity.Order, ch *amqp.Channel) {
if !stringInSlice(order.Uuid, active) {
active = append(active, order.Uuid)
go SimulatorWorker(order, ch)
} else {
fmt.Println("Order", order.Uuid, "was already completed or is on going...")
}
}
func SimulatorWorker(order entity.Order, ch *amqp.Channel) {
f, err := os.Open("destinations/" + order.Destination + ".txt")
if err != nil {
panic(err.Error())
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
data := strings.Split(scanner.Text(), ",")
json := destinationToJson(order, data[0], data[1])
time.Sleep(1 * time.Second)
queue.Notify(string(json), ch)
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
json := destinationToJson(order, "0", "0")
queue.Notify(string(json), ch)
}
func destinationToJson(order entity.Order, lat string, lng string) []byte {
dest := entity.Destination{
Order: order.Uuid,
Lat: lat,
Lng: lng,
}
json, _ := json.Marshal(dest)
return json
}
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}