netrpc_binding.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package main
  2. import (
  3. "github.com/go-kit/kit/endpoint"
  4. "golang.org/x/net/context"
  5. "github.com/cryptix/exp/todoKitSvc/reqrep"
  6. "github.com/cryptix/exp/todoKitSvc/todosvc"
  7. )
  8. type NetrpcBinding struct {
  9. ctx context.Context
  10. endpoints todosvc.Endpoints
  11. }
  12. func (b NetrpcBinding) Add(request reqrep.AddRequest, response *reqrep.AddResponse) error {
  13. var (
  14. ctx, cancel = context.WithCancel(b.ctx)
  15. errs = make(chan error, 1)
  16. responses = make(chan reqrep.AddResponse, 1)
  17. )
  18. defer cancel()
  19. go func() {
  20. resp, err := b.endpoints.Add(ctx, request)
  21. if err != nil {
  22. errs <- err
  23. return
  24. }
  25. addResp, ok := resp.(reqrep.AddResponse)
  26. if !ok {
  27. errs <- endpoint.ErrBadCast
  28. return
  29. }
  30. responses <- addResp
  31. }()
  32. select {
  33. case <-ctx.Done():
  34. return context.DeadlineExceeded
  35. case err := <-errs:
  36. return err
  37. case resp := <-responses:
  38. (*response) = resp
  39. return nil
  40. }
  41. }
  42. func (b NetrpcBinding) List(request reqrep.ListRequest, response *reqrep.ListResponse) error {
  43. var (
  44. ctx, cancel = context.WithCancel(b.ctx)
  45. errs = make(chan error, 1)
  46. responses = make(chan reqrep.ListResponse, 1)
  47. )
  48. defer cancel()
  49. go func() {
  50. resp, err := b.endpoints.List(ctx, request)
  51. if err != nil {
  52. errs <- err
  53. return
  54. }
  55. listResp, ok := resp.(reqrep.ListResponse)
  56. if !ok {
  57. errs <- endpoint.ErrBadCast
  58. return
  59. }
  60. responses <- listResp
  61. }()
  62. select {
  63. case <-ctx.Done():
  64. return context.DeadlineExceeded
  65. case err := <-errs:
  66. return err
  67. case resp := <-responses:
  68. (*response) = resp
  69. return nil
  70. }
  71. }