73 lines
1.3 KiB
Go
73 lines
1.3 KiB
Go
package encoder
|
|
|
|
import (
|
|
"encoding/json"
|
|
"encoding/xml"
|
|
"github.com/vmihailenco/msgpack/v4"
|
|
)
|
|
|
|
var (
|
|
XML xmlEncoder
|
|
JSON jsonEncoder
|
|
MsgPack msgPackEncoder
|
|
|
|
encoders = map[string]Encoder{
|
|
"json": JSON,
|
|
"xml": XML,
|
|
"msgpack": MsgPack,
|
|
}
|
|
)
|
|
|
|
// Register allows you to register your own encoders
|
|
func Register(name string, enc Encoder) {
|
|
encoders[name] = enc
|
|
}
|
|
|
|
// From will return an encoder for the specified key
|
|
func From(name string) Encoder {
|
|
if enc, ok := encoders[name]; ok {
|
|
return enc
|
|
}
|
|
|
|
return MsgPack
|
|
}
|
|
|
|
// Encoder is the base interface for encoding/decoding values
|
|
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)
|
|
}
|