cacheinterface/encoder/encoding.go
Tyler 41d0ef3d97
Some checks failed
continuous-integration/drone Build is failing
Initial v2 version, better testing, updates
2023-02-04 20:22:41 -05:00

67 lines
1.1 KiB
Go

package encoder
import (
"encoding/json"
"encoding/xml"
"github.com/vmihailenco/msgpack/v4"
)
var (
XML xmlEncoder
JSON jsonEncoder
MsgPack msgPackEncoder
)
func EncoderFrom(name string) Encoder {
var enc Encoder
switch name {
case "json":
enc = JSON
case "xml":
enc = XML
default: // Default is also msgpack
enc = MsgPack
}
return enc
}
type Encoder interface {
Unmarshal(b []byte, dest any) error
Marshal(value any) ([]byte, error)
}
type jsonEncoder struct {
}
func (j jsonEncoder) Marshal(value any) ([]byte, error) {
return json.Marshal(value)
}
func (j jsonEncoder) Unmarshal(b []byte, dest any) error {
return json.Unmarshal(b, dest)
}
type msgPackEncoder struct {
}
func (m msgPackEncoder) Marshal(value any) ([]byte, error) {
return msgpack.Marshal(value)
}
func (m msgPackEncoder) Unmarshal(b []byte, dest any) error {
return msgpack.Unmarshal(b, dest)
}
type xmlEncoder struct {
}
func (x xmlEncoder) Marshal(value any) ([]byte, error) {
return xml.Marshal(value)
}
func (x xmlEncoder) Unmarshal(b []byte, dest any) error {
return xml.Unmarshal(b, dest)
}