rpc/protocol/json/client.go

50 lines
1.3 KiB
Go
Raw Normal View History

2017-10-26 07:21:35 +00:00
package json
import (
"encoding/json"
"io"
2017-10-31 09:25:44 +00:00
2017-11-26 10:15:51 +00:00
"git.loafle.net/commons_go/rpc/codec"
2017-10-31 09:25:44 +00:00
"git.loafle.net/commons_go/rpc/protocol"
2017-10-26 07:21:35 +00:00
)
2017-10-31 09:25:44 +00:00
// ----------------------------------------------------------------------------
// Codec
// ----------------------------------------------------------------------------
// NewCustomClientCodec returns a new JSON Codec based on passed encoder selector.
2017-11-26 10:15:51 +00:00
func NewCustomClientCodec(codecSel codec.CodecSelector) protocol.ClientCodec {
return &ClientCodec{codecSel: codecSel}
2017-10-26 07:21:35 +00:00
}
2017-10-31 09:25:44 +00:00
// NewClientCodec returns a new JSON Codec.
2017-11-26 10:15:51 +00:00
func NewClientCodec() protocol.ClientCodec {
return NewCustomClientCodec(codec.DefaultCodecSelector)
2017-10-31 09:25:44 +00:00
}
// ClientCodec creates a ClientCodecRequest to process each request.
type ClientCodec struct {
2017-11-26 10:15:51 +00:00
codecSel codec.CodecSelector
2017-10-31 09:25:44 +00:00
}
2017-11-26 10:15:51 +00:00
func (cc *ClientCodec) WriteRequest(w io.Writer, method string, args interface{}, id interface{}) error {
2017-11-28 16:19:03 +00:00
req := &clientRequest{
Version: Version,
Method: method,
Params: args,
ID: id,
}
2017-10-31 09:25:44 +00:00
2017-11-26 10:15:51 +00:00
encoder := json.NewEncoder(cc.codecSel.SelectByWriter(w).Encode(w))
2017-10-31 09:25:44 +00:00
if err := encoder.Encode(req); nil != err {
2017-10-26 07:21:35 +00:00
return err
}
2017-10-31 09:25:44 +00:00
return nil
}
2017-11-26 10:15:51 +00:00
// NewMessage returns a ClientMessageCodec.
2017-11-28 16:19:03 +00:00
func (cc *ClientCodec) NewResponse(r io.Reader) (protocol.ClientResponseCodec, error) {
return newClientResponseCodec(r, cc.codecSel.SelectByReader(r))
2017-10-26 07:21:35 +00:00
}