-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcat.go
79 lines (65 loc) · 1.3 KB
/
cat.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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/ably/ably-go/ably"
)
func cat(ctx context.Context, channel *ably.RealtimeChannel) error {
var text [][]byte = [][]byte{{}}
_history := channel.History(ably.HistoryWithDirection(ably.Forwards))
history, err := _history.Items(ctx)
if err != nil {
return err
}
ok := history.Next(ctx)
if !ok {
return errors.New("No file found in session")
}
item := history.Item()
if item.Name != "new" {
return errors.New("No file found in session")
}
text = handleCatMessage(text, item)
for {
ok = history.Next(ctx)
if !ok {
break
}
item = history.Item()
text = handleCatMessage(text, item)
}
err = history.Err()
if err != nil {
return err
}
for _, line := range text {
fmt.Println(string(line))
}
return nil
}
func handleCatMessage(text [][]byte, msg *ably.Message) [][]byte {
switch msg.Name {
case "new":
msg := msg.Data.(string)
text = applyNew(msg, text)
case "add":
var add Add
data := msg.Data.(string)
err := json.Unmarshal([]byte(data), &add)
if err != nil {
break
}
text = applyAdd(add, text)
case "delete":
var del Delete
data := msg.Data.(string)
err := json.Unmarshal([]byte(data), &del)
if err != nil {
break
}
text = applyDel(del, text)
}
return text
}