1 Star 0 Fork 19

examplessssss/y3-codec-golang

forked from YoMo/y3-codec-golang 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
codec.go 1.39 KB
一键复制 编辑 原始数据 按行查看 历史
package y3
import (
"reflect"
"github.com/yomorun/y3-codec-golang/internal/utils"
)
// Codec encode the user's data according to the Y3 encoding rules
type Codec interface {
// Marshal encode interface to []byte
Marshal(input interface{}) ([]byte, error)
}
// NewCodec create a Codec interface
func NewCodec(observe byte) Codec {
return &y3Codec{
observe: observe,
}
}
// y3Codec is implementation of the Codec interface
type y3Codec struct {
observe byte
}
// Marshal encode interface to []byte
func (c y3Codec) Marshal(input interface{}) ([]byte, error) {
if c.isStruct(input) {
return newStructEncoder(c.observe,
structEncoderOptionRoot(utils.RootToken),
structEncoderOptionForbidUserKey(utils.ForbidUserKey),
structEncoderOptionAllowSignalKey(utils.AllowSignalKey)).
Encode(input)
}
return newBasicEncoder(c.observe,
basicEncoderOptionRoot(utils.RootToken),
basicEncoderOptionForbidUserKey(utils.ForbidUserKey),
basicEncoderOptionAllowSignalKey(utils.AllowSignalKey)).
Encode(input)
}
// isStruct determine whether an interface is a structure
func (c y3Codec) isStruct(mold interface{}) bool {
isStruct := false
moldValue := reflect.Indirect(reflect.ValueOf(mold))
moldType := moldValue.Type()
switch moldType.Kind() {
case reflect.Struct:
isStruct = true
case reflect.Slice:
if moldType.Elem().Kind() == reflect.Struct {
isStruct = true
}
}
return isStruct
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/py-example/y3-codec-golang.git
git@gitee.com:py-example/y3-codec-golang.git
py-example
y3-codec-golang
y3-codec-golang
master

搜索帮助

23e8dbc6 1850385 7e0993f3 1850385