You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.2 KiB
Go
58 lines
1.2 KiB
Go
2 years ago
|
package douyu
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"fmt"
|
||
|
"github.com/pkg/errors"
|
||
|
"live-gateway/douyu/stt"
|
||
|
"live-gateway/ws"
|
||
|
)
|
||
|
|
||
|
type CodecDouyu struct {
|
||
|
}
|
||
|
|
||
|
func NewCodecDouyu() ws.Codec {
|
||
|
return &CodecDouyu{}
|
||
|
}
|
||
|
|
||
|
// Encode encodes TypedData to douyu.WsEntry
|
||
|
func (c *CodecDouyu) Encode(v interface{}) (interface{}, error) {
|
||
|
data, ok := v.(TypedData)
|
||
|
if !ok {
|
||
|
return nil, errors.New("[Codec-Douyu] 写入值类型必须实现 douyu.TypedData 接口")
|
||
|
}
|
||
|
|
||
|
bf := bytes.NewBuffer([]byte{})
|
||
|
bf.WriteString(fmt.Sprintf("type@=%s/", data.DataType()))
|
||
|
|
||
|
sttData, err := stt.Marshal(v)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
bf.Write(sttData)
|
||
|
|
||
|
resp := &WsEntry{
|
||
|
data: bf.Bytes(),
|
||
|
msgType: TypeMessageToServer,
|
||
|
}
|
||
|
//logger.SLog.Debugf("发送消息: %s", string(resp.data))
|
||
|
return resp, nil
|
||
|
}
|
||
|
|
||
|
func (c *CodecDouyu) Decode(customEntry interface{}) (interface{}, error) {
|
||
|
// 处理data
|
||
|
entry, ok := customEntry.(*WsEntry)
|
||
|
if !ok {
|
||
|
return nil, errors.New(fmt.Sprintf("[Codec-Douyu] 写入值类型必须为%T", WsEntry{}))
|
||
|
}
|
||
|
var typed struct {
|
||
|
Type string `stt:"type"`
|
||
|
}
|
||
|
err := stt.Unmarshal(entry.data, &typed)
|
||
|
if err != nil {
|
||
|
return nil, errors.New("[Codec-Douyu] 获取type字段失败")
|
||
|
}
|
||
|
entry.dataType = typed.Type
|
||
|
return entry, nil
|
||
|
}
|