-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatWriter.go
56 lines (45 loc) · 1.13 KB
/
chatWriter.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
package main
import (
"bytes"
"context"
"encoding/json"
"log"
"os"
"stream-downloader/chat"
"time"
"github.com/klauspost/compress/zstd"
)
func formatChatMessage(msg chat.Message, time time.Time) ([]byte, error) {
var buf bytes.Buffer
bytes, err := time.MarshalText()
if err != nil {
return []byte{}, err
}
buf.Write(bytes)
buf.WriteByte(' ')
enc := json.NewEncoder(&buf)
if err := enc.Encode(msg); err != nil {
return []byte{}, err
}
return buf.Bytes(), nil
}
// takes ownership of f, borrows chatClient
func chatRoutine(ctx context.Context, f *os.File, channel string, chatClient *chat.Client) {
defer f.Close()
wr, err := zstd.NewWriter(f, zstd.WithEncoderLevel(zstd.SpeedBestCompression))
if err != nil {
panic(err)
}
defer wr.Close()
chatClient.AddChatFunction(channel, func(msg chat.Message, time time.Time) {
line, err := formatChatMessage(msg, time)
if err != nil {
log.Printf("error while marshalling message: %s", err)
}
if _, err := wr.Write(line); err != nil {
log.Printf("error while writing chat message to file: %s", err)
}
})
defer chatClient.RemoveChatFunction(channel)
<-ctx.Done()
}