forked from direnv/direnv
-
Notifications
You must be signed in to change notification settings - Fork 2
/
marshal.go
57 lines (45 loc) · 1.1 KB
/
marshal.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
package main
import (
"bytes"
"compress/zlib"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"strings"
)
func marshal(obj interface{}) string {
jsonData, err := json.Marshal(obj)
if err != nil {
panic(fmt.Errorf("marshal(): %v", err))
}
zlibData := bytes.NewBuffer([]byte{})
w := zlib.NewWriter(zlibData)
w.Write(jsonData)
w.Close()
base64Data := base64.URLEncoding.EncodeToString(zlibData.Bytes())
return base64Data
}
func unmarshal(base64env string, obj interface{}) error {
base64env = strings.TrimSpace(base64env)
data, err := base64.URLEncoding.DecodeString(base64env)
if err != nil {
return fmt.Errorf("unmarshal() base64 decoding: %v", err)
}
zlibReader := bytes.NewReader(data)
w, err := zlib.NewReader(zlibReader)
if err != nil {
return fmt.Errorf("unmarshal() zlib opening: %v", err)
}
envData := bytes.NewBuffer([]byte{})
_, err = io.Copy(envData, w)
if err != nil {
return fmt.Errorf("unmarshal() zlib decoding: %v", err)
}
w.Close()
err = json.Unmarshal(envData.Bytes(), &obj)
if err != nil {
return fmt.Errorf("unmarshal() json parsing: %v", err)
}
return nil
}