-
Notifications
You must be signed in to change notification settings - Fork 0
/
codecs.go
38 lines (30 loc) · 857 Bytes
/
codecs.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
// Codes: encode/decode to process structures to []byte and back
package main
import (
"bytes"
"encoding/gob" // https://golang.org/pkg/encoding/gob/
)
// get interface structure end encode it to []byte result
// input: interface{}
// output: []byte
func encode(obj interface{}) []byte {
//var buf bytes.Buffer
buf := new(bytes.Buffer)
err := gob.NewEncoder(buf).Encode(obj)
if err != nil {
panic(err)
}
return buf.Bytes() //get the result out as a []byte
}
// get []byte source and interface structure end decode to interface{}
// output: interface{}
// input: []byte
func decode(objx interface{}, src []byte) {
// make a reader for the input (which is a []byte)
p := bytes.NewReader(src)
err := gob.NewDecoder(p).Decode(objx)
if err != nil {
panic(err)
}
}
// todo: panic recover @decode error, must send back errror and continue