381ce2cf3ede8e1f1e1f61bb98c34352d94c990e.svn-base 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package endpoint
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/go-kit/kit/endpoint"
  6. "github.com/longjoy/micro-go-course/section28/goods/service"
  7. "golang.org/x/time/rate"
  8. "log"
  9. )
  10. type GoodsEndpoints struct {
  11. GoodsDetailEndpoint endpoint.Endpoint
  12. HealthCheckEndpoint endpoint.Endpoint
  13. }
  14. // 服务发现请求结构体
  15. type GoodsDetailRequest struct {
  16. Id string
  17. }
  18. // 服务发现响应结构体
  19. type GoodsDetailResponse struct {
  20. Detail service.GoodsDetailVO `json:"detail"`
  21. Error string `json:"error"`
  22. }
  23. // 创建服务发现的 Endpoint
  24. func MakeGoodsDetailEndpoint(svc service.Service, limiter *rate.Limiter) endpoint.Endpoint {
  25. return func(ctx context.Context, request interface{}) (response interface{}, err error) {
  26. if !limiter.Allow() {
  27. // Allow返回false,表示桶内不足一个令牌,应该被限流,默认返回 ErrLimiExceed 异常
  28. return nil, errors.New("ErrLimitExceed")
  29. }
  30. req := request.(GoodsDetailRequest)
  31. detail, err := svc.GetGoodsDetail(ctx, req.Id)
  32. var errString = ""
  33. if err != nil {
  34. errString = err.Error()
  35. return &GoodsDetailResponse{
  36. Detail: detail,
  37. Error: errString,
  38. }, nil
  39. }
  40. return &GoodsDetailResponse{
  41. Detail: detail,
  42. Error: errString,
  43. }, nil
  44. }
  45. }
  46. // HealthRequest 健康检查请求结构
  47. type HealthRequest struct{}
  48. // HealthResponse 健康检查响应结构
  49. type HealthResponse struct {
  50. Status string `json:"status"`
  51. }
  52. // MakeHealthCheckEndpoint 创建健康检查Endpoint
  53. func MakeHealthCheckEndpoint(svc service.Service) endpoint.Endpoint {
  54. return func(ctx context.Context, request interface{}) (response interface{}, err error) {
  55. log.Printf("helthcheck")
  56. status := svc.HealthCheck()
  57. return HealthResponse{
  58. Status: status,
  59. }, nil
  60. }
  61. }