-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserialize.go
More file actions
66 lines (59 loc) · 2.02 KB
/
serialize.go
File metadata and controls
66 lines (59 loc) · 2.02 KB
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
// Package serializer provides tools to serialize any kind of data using Gob + Base64
package serializer
import (
"bytes"
"encoding/base64"
"encoding/gob"
)
// SerializeToGob serializes the given interface to an array of bytes
// using Gob for serialization
// Returns an array of serialized bytes or an error
// Error is nil if the serialization succeeds
func SerializeToGob(value interface{}) ([]byte, error) {
buf := new(bytes.Buffer)
enc := gob.NewEncoder(buf)
if err := enc.Encode(value); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// DeserializeFromGob deserializes bytes in gob encoding to an interface
// value contains the deserialized object
// Returns nil if succeeds
func DeserializeFromGob(serialized []byte, value interface{}) error {
dec := gob.NewDecoder(bytes.NewBuffer(serialized))
if err := dec.Decode(value); err != nil {
return err
}
return nil
}
// SerializeInterfaceToString serializes the given interface into a string
// It first encodes in gob, and then returns a base64 encoded string for the bytes
func SerializeInterfaceToString(value interface{}) (string, error) {
bytes, err := SerializeToGob(value)
if (err != nil) {
return "", err
}
return ByteToBase64String(bytes), nil
}
// DeserializeStringToInterface deserializes a base 64 string into the interface
// The input string must be the base64 encoding of gob output
func DeserializeStringToInterface(serialized string, value interface{}) error {
bytes, err := Base64StringToByte(serialized)
if (err != nil) {
return err
}
err = DeserializeFromGob(bytes, value)
if (err != nil) {
return err
}
return nil
}
// ByteToBase64String encodes to Base64 using URLEncoding
func ByteToBase64String(bytes []byte) string {
return base64.URLEncoding.EncodeToString(bytes)
}
// Base64StringToByte decodes the input base64 string into bytes
func Base64StringToByte(str string) ([]byte, error) {
return base64.URLEncoding.DecodeString(str)
}