/
codec.go
52 lines (46 loc) · 944 Bytes
/
codec.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
package codec
import (
"bytes"
"encoding/json"
"errors"
"github.com/BurntSushi/toml"
)
/**
* Encode data based on format
* Currently supported: toml and json
*/
func Encode(in interface{}, out *string, format string) error {
switch format {
case "toml":
buf := new(bytes.Buffer)
if err := toml.NewEncoder(buf).Encode(in); err != nil {
return err
}
*out = buf.String()
return nil
case "json":
buf, err := json.MarshalIndent(in, "", " ")
if err != nil {
return err
}
*out = string(buf)
return nil
default:
return errors.New("Unknown format " + format)
}
}
/**
* Decode data based on format
* Currently supported: toml and json
*/
func Decode(data string, out interface{}, format string) error {
switch format {
case "toml":
_, err := toml.Decode(data, out)
return err
case "json":
return json.Unmarshal([]byte(data), out)
default:
return errors.New("Unknown format " + format)
}
}