Last active
August 9, 2016 13:18
-
-
Save Dynom/73fec7710c9790bcfb01b73ecabd2e90 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"github.com/go-kit/kit/endpoint" | |
"github.com/go-kit/kit/log" | |
"golang.org/x/net/context" | |
// ... | |
) | |
func MakeJSONRPCEndpoint(registry RPCMethodRegistry, logger log.Logger) endpoint.Endpoint { | |
return func(_ context.Context, request interface{}) (interface{}, error) { | |
typedRequest := request.(JSONRPCRequest) | |
response := JSONRPCResponse{ | |
ID: typedRequest.ID, | |
Version: typedRequest.Version, | |
} | |
method := JSONRPCMethod(typedRequest.Method) | |
if !registry.HasMethod(method) { | |
response.Error = JSONRPCError{ | |
Message: `Method ` + typedRequest.Method + ` doesn't exist`, | |
Code: JSONRPCErrMethodNotFound, | |
} | |
logger.Log(`method`, typedRequest.Method, `msg`, response.Error) | |
return response, nil | |
} | |
logger.Log(`method`, typedRequest.Method, `params`, string(*typedRequest.Params)) | |
cb := registry.GetMethod(method) | |
v, err := cb(typedRequest.Params) | |
if err != nil { | |
response.Error = JSONRPCError{ | |
Message: err.Error(), | |
Code: JSONRPCErrMethodNotFound, | |
} | |
return response, nil | |
} | |
response.Result = v.Result | |
return response, nil | |
} | |
} | |
// .. | |
type JSONRPCRequest struct { | |
Version string `json:"jsonrpc"` | |
Method string `json:"method"` | |
Params *json.RawMessage `json:"params"` | |
ID *json.RawMessage `json:"id"` | |
} | |
type JSONRPCResponse struct { | |
Version string `json:"jsonrpc"` | |
ID *json.RawMessage `json:"id"` | |
Result interface{} `json:"result,omitempty"` | |
Error JSONRPCError `json:"error,omitempty"` | |
} | |
type JSONRPCError struct { | |
Code int `json:"code,omitempty"` | |
Message string `json:"message,omitempty"` | |
Data interface{} `json:"data,omitempty"` | |
} | |
// .. | |
methodRegistry.AddMethod( | |
myjsonrpc.JSONRPCMethod(`items.getAll`), | |
func(r myjsonrpc.ServiceRegistry, p *json.RawMessage, l log.Logger) (myjsonrpc.ServiceResponse, error) { | |
var err error | |
var result interface{} | |
var params = items.GetAllParams{} | |
if err = myjsonrpc.MakeParameters(p, ¶ms); err == nil { | |
result, err = r.GetService(items.ServiceName).(items.Service).GetAll(params) | |
} | |
return myjsonrpc.ServiceResponse{ | |
Result: result, | |
}, err | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment