rpc/protocol/json/client_response.go

80 lines
1.8 KiB
Go
Raw Normal View History

2017-10-31 09:25:44 +00:00
package json
import (
"encoding/json"
"fmt"
"sync"
"git.loafle.net/commons_go/rpc/protocol"
)
// ----------------------------------------------------------------------------
// ClientCodecResponse
// ----------------------------------------------------------------------------
// newClientCodecResponse returns a new ClientCodecResponse.
2017-11-01 08:13:23 +00:00
func newClientCodecResponse(raw json.RawMessage) (protocol.ClientCodecResponse, error) {
2017-10-31 09:25:44 +00:00
// Decode the request body and check if RPC method is valid.
ccr := retainClientCodecResponse()
2017-11-01 08:13:23 +00:00
err := json.Unmarshal(raw, &ccr.response)
2017-10-31 09:25:44 +00:00
if err != nil {
releaseClientCodecResponse(ccr)
return nil, err
}
if nil == ccr.response.ID {
releaseClientCodecResponse(ccr)
return nil, fmt.Errorf("This is not Response")
}
if ccr.response.Version != Version {
ccr.err = &Error{
Code: E_INVALID_REQ,
Message: "jsonrpc must be " + Version,
Data: ccr.response,
}
}
return ccr, nil
}
// ClientCodecResponse decodes and encodes a single request.
type ClientCodecResponse struct {
response clientResponse
err error
}
func (ccr *ClientCodecResponse) ID() interface{} {
return ccr.response.ID
}
func (ccr *ClientCodecResponse) Result() interface{} {
return ccr.response.Result
}
func (ccr *ClientCodecResponse) Error() error {
return ccr.response.Error.(error)
}
func (ccr *ClientCodecResponse) Complete() {
releaseClientCodecResponse(ccr)
}
var clientCodecResponsePool sync.Pool
func retainClientCodecResponse() *ClientCodecResponse {
v := clientCodecResponsePool.Get()
if v == nil {
return &ClientCodecResponse{}
}
return v.(*ClientCodecResponse)
}
func releaseClientCodecResponse(ccr *ClientCodecResponse) {
ccr.response.Version = ""
ccr.response.Result = nil
ccr.response.Error = nil
ccr.response.ID = nil
clientCodecResponsePool.Put(ccr)
}