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.

69 lines
1.4 KiB

  1. package jsonrpc
  2. import (
  3. "bytes"
  4. "context"
  5. "io"
  6. "log"
  7. "net/http"
  8. "net/http/httptest"
  9. "os"
  10. "github.com/intel-go/fastjson"
  11. )
  12. type (
  13. EchoHandler struct{}
  14. EchoParams struct {
  15. Name string `json:"name"`
  16. }
  17. EchoResult struct {
  18. Message string `json:"message"`
  19. }
  20. )
  21. func (h EchoHandler) ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (interface{}, *Error) {
  22. var p EchoParams
  23. if err := Unmarshal(params, &p); err != nil {
  24. return nil, err
  25. }
  26. return EchoResult{
  27. Message: "Hello, " + p.Name,
  28. }, nil
  29. }
  30. func ExampleEchoHandler_ServeJSONRPC() {
  31. mr := NewMethodRepository()
  32. if err := mr.RegisterMethod("Main.Echo", EchoHandler{}, EchoParams{}, EchoResult{}); err != nil {
  33. log.Fatalln(err)
  34. }
  35. http.Handle("/jrpc", mr)
  36. http.HandleFunc("/jrpc/debug", mr.ServeDebug)
  37. srv := httptest.NewServer(http.DefaultServeMux)
  38. defer srv.Close()
  39. resp, err := http.Post(srv.URL+"/jrpc", "application/json", bytes.NewBufferString(`{
  40. "jsonrpc": "2.0",
  41. "method": "Main.Echo",
  42. "params": {
  43. "name": "John Doe"
  44. },
  45. "id": "243a718a-2ebb-4e32-8cc8-210c39e8a14b"
  46. }`))
  47. if err != nil {
  48. log.Fatalln(err)
  49. }
  50. defer resp.Body.Close()
  51. if _, err := io.Copy(os.Stdout, resp.Body); err != nil {
  52. log.Fatalln(err)
  53. }
  54. // Output:
  55. // {"id":"243a718a-2ebb-4e32-8cc8-210c39e8a14b","jsonrpc":"2.0","result":{"message":"Hello, John Doe"}}
  56. }