ex3rpc.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package main
  2. /*
  3. Sample request content:
  4. Method: POST
  5. Content-type: application/json -> without it JSON-RPC returns a 415.
  6. Accept header is not needed.
  7. {
  8. "method": "StringService.Length",
  9. "params" : [
  10. {
  11. "Message": "Hello, world"
  12. }
  13. ],
  14. "id": 1
  15. }
  16. Sample Curl usage:
  17. curl -X POST -H "Content-type: application/json" -d '{"method": "StringService.Length", "params": [{"Message": "Hello, world"}], "Id": 1}' http://localhost:8080/rpc
  18. */
  19. import (
  20. "net/http"
  21. "github.com/gorilla/rpc/v2"
  22. "github.com/gorilla/rpc/v2/json"
  23. "fmt"
  24. "unicode/utf8"
  25. "github.com/davecgh/go-spew/spew"
  26. )
  27. type RPCApiArguments struct {
  28. Message string
  29. }
  30. type RPCAPIResponse struct {
  31. Message string
  32. }
  33. type StringService struct{}
  34. func (s *StringService) Length(q *http.Request, args *RPCApiArguments, r *RPCAPIResponse) error {
  35. r.Message = fmt.Sprintf("Your request [%s] is %d characters long",
  36. args.Message,
  37. utf8.RuneCountInString(args.Message))
  38. spew.Dump(r)
  39. return nil
  40. }
  41. func main() {
  42. address := ":8080"
  43. fmt.Printf("API started on %s\n", address)
  44. s := rpc.NewServer()
  45. s.RegisterCodec(json.NewCodec(), "application/json")
  46. s.RegisterService(new(StringService), "")
  47. http.Handle("/rpc", s)
  48. http.ListenAndServe(address, nil)
  49. }