-
Notifications
You must be signed in to change notification settings - Fork 1
/
transformers.go
49 lines (44 loc) · 904 Bytes
/
transformers.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
package memo
import (
"bytes"
"compress/zlib"
"encoding/json"
"io"
"strings"
)
func toJson(key string) Transformer {
return func(value string) (string, error) {
data := make(map[string]string)
var b bytes.Buffer
w := zlib.NewWriter(&b)
w.Write([]byte(value))
w.Close()
compressed := b.Bytes()
data[key] = string(compressed)
bz, err := json.Marshal(data)
return string(bz), err
}
}
func fromJson(key string) Transformer {
return func(memo string) (string, error) {
data := make(map[string]string)
err := json.Unmarshal([]byte(memo), &data)
if err != nil {
return "", err
}
compressed, ok := data[key]
if !ok {
return "", nil
}
r, err := zlib.NewReader(strings.NewReader(compressed))
if err != nil {
return "", err
}
buf := new(strings.Builder)
_, err = io.Copy(buf, r)
if err != nil {
return "", err
}
return buf.String(), nil
}
}