-
Notifications
You must be signed in to change notification settings - Fork 9
/
bytes.go
77 lines (67 loc) · 1.39 KB
/
bytes.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
package toolkit
import (
"bytes"
"encoding/gob"
"errors"
"strings"
)
func ToBytesWithError(data interface{}, encoderId string) ([]byte, error) {
encoderId = strings.ToLower(encoderId)
if encoderId == "" {
encoderId = "json"
}
if encoderId == "json" {
return Jsonify(data), nil
} else if encoderId == "gob" {
b, e := EncodeByte(data)
if e != nil {
return nil, errors.New(e.Error())
} else {
return b, nil
}
}
return nil, errors.New("Invalid encoderId method")
}
func ToBytes(data interface{}, encoderId string) []byte {
b, e := ToBytesWithError(data, encoderId)
if e != nil {
return []byte{}
} else {
return b
}
}
func FromBytes(b []byte, decoderId string, out interface{}) error {
var e error
decoderId = strings.ToLower(decoderId)
if decoderId == "" {
decoderId = "json"
}
if decoderId == "json" {
e = Unjson(b, out)
} else {
e = DecodeByte(b, out)
}
return e
}
func DecodeByte(bytesData []byte, result interface{}) error {
buf := bytes.NewBuffer(bytesData)
dec := gob.NewDecoder(buf)
e := dec.Decode(result)
return e
}
func GetEncodeByte(obj interface{}) []byte {
b, e := EncodeByte(obj)
if e != nil {
return new(bytes.Buffer).Bytes()
}
return b
}
func EncodeByte(obj interface{}) ([]byte, error) {
buf := new(bytes.Buffer)
gw := gob.NewEncoder(buf)
err := gw.Encode(obj)
if err != nil {
return buf.Bytes(), err
}
return buf.Bytes(), nil
}