router.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package service
  2. import (
  3. "context"
  4. "git.chuangxin1.com/csacred/toolkit/example/cuser/define"
  5. "git.chuangxin1.com/csacred/toolkit/http"
  6. "github.com/go-kit/kit/log"
  7. consulsd "github.com/go-kit/kit/sd/consul"
  8. )
  9. // API gateway factory
  10. func factory(ctx context.Context, instancer *consulsd.Instancer, logger log.Logger) Endpoints {
  11. e := Endpoints{}
  12. var lb http.LoadBalancer
  13. lb.Logger = logger
  14. lb.Ctx = ctx
  15. lb.Inst = instancer
  16. lb.Dec = http.DecodeJSONResponse
  17. lb.Route = define.RouteUserGetProfile
  18. e.UserProfileEndpoint = http.GetLoadBalancer(lb)
  19. lb.Route = define.RouteUserGetList
  20. e.UserListEndpoint = http.GetLoadBalancer(lb)
  21. lb.Route = define.RouteUserPostSignIn
  22. e.UserSignInEndpoint = http.PostLoadBalancer(lb)
  23. lb.Route = define.RouteUserPostChangePwd
  24. e.UserChangePwdEndpoint = http.PostLoadBalancer(lb)
  25. return e
  26. }
  27. func endpointHanders(endpoints Endpoints) []http.EndpointRouter {
  28. var handers []http.EndpointRouter
  29. handers = append(handers, http.GetEndpointRouter(define.RouteUserGetProfile, DecodeGetUserProfileRequest, http.WriteCtxJSON, endpoints.UserProfileEndpoint))
  30. handers = append(handers, http.GetEndpointRouter(define.RouteUserGetList, DecodeGetUserListRequest, http.WriteCtxJSON, endpoints.UserListEndpoint))
  31. handers = append(handers, http.PostEndpointRouter(define.RouteUserPostSignIn, DecodePostUserSignInRequest, http.WriteCtxJSON, endpoints.UserSignInEndpoint))
  32. handers = append(handers, http.PostEndpointRouter(define.RouteUserPostChangePwd, DecodePostUserChangePwdRequest, http.WriteCtxJSON, endpoints.UserChangePwdEndpoint))
  33. return handers
  34. }
  35. // GenServiceHandler service handler
  36. func GenServiceHandler(s UserServicer, logger log.Logger) []http.RouterHandler {
  37. var handers []http.RouterHandler
  38. e := GenServerEndpoints(s)
  39. ehanders := endpointHanders(e)
  40. for i := range ehanders {
  41. handers = append(handers, http.EndpointRouterHandler(ehanders[i], logger))
  42. }
  43. return handers
  44. }
  45. // GenGatewayHandlers gateway handlers
  46. func GenGatewayHandlers(ctx context.Context, instancer *consulsd.Instancer, logger log.Logger) []http.RouterHandler {
  47. var handers []http.RouterHandler
  48. e := factory(ctx, instancer, logger)
  49. ehanders := endpointHanders(e)
  50. for i := range ehanders {
  51. handers = append(handers, http.EndpointRouterHandler(ehanders[i], logger))
  52. }
  53. return handers
  54. }