-
Notifications
You must be signed in to change notification settings - Fork 6
/
consumer.go
86 lines (76 loc) · 2.06 KB
/
consumer.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
package main
import (
"bufio"
"encoding/json"
"fmt"
"github.com/Shopify/sarama"
"os"
)
func mainConsumer(partition int32) {
kafka := newKafkaConsumer()
defer kafka.Close()
consumer, err := kafka.ConsumePartition(topic, partition, sarama.OffsetOldest)
if err != nil {
fmt.Printf("Kafka error: %s\n", err)
os.Exit(-1)
}
go consumeEvents(consumer)
fmt.Println("Press [enter] to exit consumer\n")
bufio.NewReader(os.Stdin).ReadString('\n')
fmt.Println("Terminating...")
}
func consumeEvents(consumer sarama.PartitionConsumer) {
var msgVal []byte
var log interface{}
var logMap map[string]interface{}
var bankAccount *BankAccount
var err error
for {
select {
case err := <-consumer.Errors():
fmt.Printf("Kafka error: %s\n", err)
case msg := <-consumer.Messages():
msgVal = msg.Value
if err = json.Unmarshal(msgVal, &log); err != nil {
fmt.Printf("Failed parsing: %s", err)
} else {
logMap = log.(map[string]interface{})
logType := logMap["Type"]
fmt.Printf("Processing %s:\n%s\n", logMap["Type"], string(msgVal))
switch logType {
case "CreateEvent":
event := new(CreateEvent)
if err = json.Unmarshal(msgVal, &event); err == nil {
bankAccount, err = event.Process()
}
case "DepositEvent":
event := new(DepositEvent)
if err = json.Unmarshal(msgVal, &event); err == nil {
bankAccount, err = event.Process()
}
case "WithdrawEvent":
event := new(WithdrawEvent)
if err = json.Unmarshal(msgVal, &event); err == nil {
bankAccount, err = event.Process()
}
case "TransferEvent":
event := new(TransferEvent)
if err = json.Unmarshal(msgVal, &event); err == nil {
if bankAccount, err = event.Process(); err == nil {
if targetAcc, err := FetchAccount(event.TargetId); err == nil {
fmt.Printf("%+v\n", *targetAcc)
}
}
}
default:
fmt.Println("Unknown command: ", logType)
}
if err != nil {
fmt.Printf("Error processing: %s\n", err)
} else {
fmt.Printf("%+v\n\n", *bankAccount)
}
}
}
}
}