You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.1 KiB

  1. package jsonrpc
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/intel-go/fastjson"
  6. )
  7. // Handler links a method of JSON-RPC request.
  8. type Handler interface {
  9. ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (result interface{}, err *Error)
  10. }
  11. // ServeHTTP provides basic JSON-RPC handling.
  12. func (mr *MethodRepository) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  13. rs, batch, err := ParseRequest(r)
  14. if err != nil {
  15. SendResponse(w, []*Response{
  16. {
  17. Version: Version,
  18. Error: err,
  19. },
  20. }, false)
  21. return
  22. }
  23. resp := make([]*Response, len(rs))
  24. for i := range rs {
  25. resp[i] = mr.InvokeMethod(r.Context(), rs[i])
  26. }
  27. if err := SendResponse(w, resp, batch); err != nil {
  28. w.WriteHeader(http.StatusInternalServerError)
  29. }
  30. }
  31. // InvokeMethod invokes JSON-RPC method.
  32. func (mr *MethodRepository) InvokeMethod(c context.Context, r *Request) *Response {
  33. var h Handler
  34. res := NewResponse(r)
  35. h, res.Error = mr.TakeMethod(r)
  36. if res.Error != nil {
  37. return res
  38. }
  39. res.Result, res.Error = h.ServeJSONRPC(WithRequestID(c, r.ID), r.Params)
  40. if res.Error != nil {
  41. res.Result = nil
  42. }
  43. return res
  44. }