You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1.0 KiB
41 lines
1.0 KiB
package shock |
|
|
|
import ( |
|
"bytes" |
|
"encoding/gob" |
|
"encoding/json" |
|
) |
|
|
|
// Serializer defines a way to encode/decode objects in the database |
|
type Serializer interface { |
|
Marshal(v interface{}) ([]byte, error) |
|
Unmarshal(data []byte, v interface{}) error |
|
} |
|
|
|
// JSONSerializer is a Serializer that uses JSON |
|
type JSONSerializer struct{} |
|
|
|
// Marshal encodes an object to JSON |
|
func (j JSONSerializer) Marshal(v interface{}) ([]byte, error) { |
|
return json.Marshal(v) |
|
} |
|
|
|
// Unmarshal decodes an object from JSON |
|
func (j JSONSerializer) Unmarshal(data []byte, v interface{}) error { |
|
return json.Unmarshal(data, &v) |
|
} |
|
|
|
// GobSerializer is a Serializer that uses gob |
|
type GobSerializer struct{} |
|
|
|
// Marshal encodes an object to gob |
|
func (g GobSerializer) Marshal(v interface{}) ([]byte, error) { |
|
var buf bytes.Buffer |
|
err := gob.NewEncoder(&buf).Encode(v) |
|
return buf.Bytes(), err |
|
} |
|
|
|
// Unmarshal decodes an object from gob |
|
func (g GobSerializer) Unmarshal(data []byte, v interface{}) error { |
|
return gob.NewDecoder(bytes.NewBuffer(data)).Decode(v) |
|
}
|
|
|