endpoints.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package endpoint
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/go-kit/kit/endpoint"
  6. "github.com/longjoy/micro-go-course/section35/zipkin-kit/string-service/service"
  7. "strings"
  8. )
  9. // StringEndpoint define endpoint
  10. type StringEndpoints struct {
  11. StringEndpoint endpoint.Endpoint
  12. HealthCheckEndpoint endpoint.Endpoint
  13. }
  14. func (se StringEndpoints) Concat(a, b string) (string, error) {
  15. ctx := context.Background()
  16. resp, err := se.StringEndpoint(ctx, StringRequest{
  17. RequestType: "Concat",
  18. A: a,
  19. B: b,
  20. })
  21. response := resp.(StringResponse)
  22. return response.Result, err
  23. }
  24. func (se StringEndpoints) Diff(ctx context.Context, a, b string) (string, error) {
  25. resp, err := se.StringEndpoint(ctx, StringRequest{
  26. RequestType: "Diff",
  27. A: a,
  28. B: b,
  29. })
  30. response := resp.(StringResponse)
  31. return response.Result, err
  32. }
  33. func (StringEndpoints) HealthCheck() bool {
  34. return false
  35. }
  36. var (
  37. ErrInvalidRequestType = errors.New("RequestType has only two type: Concat, Diff")
  38. )
  39. // StringRequest define request struct
  40. type StringRequest struct {
  41. RequestType string `json:"request_type"`
  42. A string `json:"a"`
  43. B string `json:"b"`
  44. }
  45. // StringResponse define response struct
  46. type StringResponse struct {
  47. Result string `json:"result"`
  48. Error error `json:"error"`
  49. }
  50. // MakeStringEndpoint make endpoint
  51. func MakeStringEndpoint(ctx context.Context, svc service.Service) endpoint.Endpoint {
  52. return func(ctx1 context.Context, request interface{}) (response interface{}, err error) {
  53. req := request.(StringRequest)
  54. var (
  55. res, a, b string
  56. opError error
  57. )
  58. a = req.A
  59. b = req.B
  60. if strings.EqualFold(req.RequestType, "Concat") {
  61. res, _ = svc.Concat(a, b)
  62. } else if strings.EqualFold(req.RequestType, "Diff") {
  63. res, _ = svc.Diff(ctx, a, b)
  64. } else {
  65. return nil, ErrInvalidRequestType
  66. }
  67. return StringResponse{Result: res, Error: opError}, nil
  68. }
  69. }
  70. // HealthRequest 健康检查请求结构
  71. type HealthRequest struct{}
  72. // HealthResponse 健康检查响应结构
  73. type HealthResponse struct {
  74. Status bool `json:"status"`
  75. }
  76. // MakeHealthCheckEndpoint 创建健康检查Endpoint
  77. func MakeHealthCheckEndpoint(svc service.Service) endpoint.Endpoint {
  78. return func(ctx context.Context, request interface{}) (response interface{}, err error) {
  79. status := svc.HealthCheck()
  80. return HealthResponse{status}, nil
  81. }
  82. }