rpc/protocol/json/client.go
crusader 4fe1fa640d ing
2018-03-23 12:22:16 +09:00

55 lines
1.4 KiB
Go

package json
import (
"io"
"git.loafle.net/commons_go/rpc/codec"
"git.loafle.net/commons_go/rpc/protocol"
jsoniter "github.com/json-iterator/go"
)
// ----------------------------------------------------------------------------
// Codec
// ----------------------------------------------------------------------------
// NewCustomClientCodec returns a new JSON Codec based on passed encoder selector.
func NewCustomClientCodec(codecSel codec.CodecSelector) protocol.ClientCodec {
return &ClientCodec{codecSel: codecSel}
}
// NewClientCodec returns a new JSON Codec.
func NewClientCodec() protocol.ClientCodec {
return NewCustomClientCodec(codec.DefaultCodecSelector)
}
// ClientCodec creates a ClientCodecRequest to process each request.
type ClientCodec struct {
codecSel codec.CodecSelector
}
func (cc *ClientCodec) WriteRequest(w io.Writer, method string, args []interface{}, id interface{}) error {
params, err := convertParamsToStringArray(args)
if nil != err {
return err
}
req := &clientRequest{
Version: Version,
Method: method,
Params: params,
ID: id,
}
encoder := jsoniter.NewEncoder(cc.codecSel.SelectByWriter(w).Encode(w))
if err := encoder.Encode(req); nil != err {
return err
}
return nil
}
// NewMessage returns a ClientMessageCodec.
func (cc *ClientCodec) NewResponse(r io.Reader) (protocol.ClientResponseCodec, error) {
return newClientResponseCodec(r, cc.codecSel.SelectByReader(r))
}