rpc/protocol/json/client_response.go
crusader f60a2f912a ing
2017-11-23 18:16:40 +09:00

88 lines
2.1 KiB
Go

package json
import (
"encoding/json"
"fmt"
"sync"
"git.loafle.net/commons_go/rpc/protocol"
)
// ----------------------------------------------------------------------------
// ClientCodecResponse
// ----------------------------------------------------------------------------
// newClientCodecResponse returns a new ClientCodecResponse.
func newClientCodecResponse(raw json.RawMessage) (protocol.ClientCodecResponse, error) {
// Decode the request body and check if RPC method is valid.
ccr := retainClientCodecResponse()
err := json.Unmarshal(raw, &ccr.response)
if err != nil {
releaseClientCodecResponse(ccr)
return nil, err
}
if nil == ccr.response.Result && nil == ccr.response.Error {
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(result interface{}) error {
if ccr.err == nil && ccr.response.Result != nil {
if err := json.Unmarshal(*ccr.response.Result, &result); err != nil {
params := [1]interface{}{result}
if err = json.Unmarshal(*ccr.response.Result, &params); err != nil {
ccr.err = err
}
}
}
return ccr.err
}
func (ccr *ClientCodecResponse) Error() error {
return ccr.response.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 = 0
clientCodecResponsePool.Put(ccr)
}