server.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. package gateway
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/fullstorydev/grpcurl"
  9. "github.com/golang/protobuf/jsonpb"
  10. "github.com/jhump/protoreflect/grpcreflect"
  11. "github.com/zeromicro/go-zero/core/logx"
  12. "github.com/zeromicro/go-zero/core/mr"
  13. "github.com/zeromicro/go-zero/gateway/internal"
  14. "github.com/zeromicro/go-zero/rest"
  15. "github.com/zeromicro/go-zero/rest/httpx"
  16. "github.com/zeromicro/go-zero/zrpc"
  17. "google.golang.org/grpc/reflection/grpc_reflection_v1alpha"
  18. )
  19. // Server is a gateway server.
  20. type Server struct {
  21. *rest.Server
  22. upstreams []upstream
  23. timeout time.Duration
  24. }
  25. // MustNewServer creates a new gateway server.
  26. func MustNewServer(c GatewayConf) *Server {
  27. return &Server{
  28. Server: rest.MustNewServer(c.RestConf),
  29. upstreams: c.Upstreams,
  30. timeout: c.Timeout,
  31. }
  32. }
  33. // Start starts the gateway server.
  34. func (s *Server) Start() {
  35. logx.Must(s.build())
  36. s.Server.Start()
  37. }
  38. // Stop stops the gateway server.
  39. func (s *Server) Stop() {
  40. s.Server.Stop()
  41. }
  42. func (s *Server) build() error {
  43. return mr.MapReduceVoid(func(source chan<- interface{}) {
  44. for _, up := range s.upstreams {
  45. source <- up
  46. }
  47. }, func(item interface{}, writer mr.Writer, cancel func(error)) {
  48. up := item.(upstream)
  49. cli := zrpc.MustNewClient(up.Grpc)
  50. source, err := s.createDescriptorSource(cli, up)
  51. if err != nil {
  52. cancel(err)
  53. return
  54. }
  55. methods, err := internal.GetMethods(source)
  56. if err != nil {
  57. cancel(err)
  58. return
  59. }
  60. methodSet := make(map[string]struct{})
  61. for _, m := range methods {
  62. methodSet[m] = struct{}{}
  63. }
  64. resolver := grpcurl.AnyResolverFromDescriptorSource(source)
  65. for _, m := range up.Mapping {
  66. if _, ok := methodSet[m.RpcPath]; !ok {
  67. cancel(fmt.Errorf("rpc method %s not found", m.RpcPath))
  68. return
  69. }
  70. writer.Write(rest.Route{
  71. Method: strings.ToUpper(m.Method),
  72. Path: m.Path,
  73. Handler: s.buildHandler(source, resolver, cli, m),
  74. })
  75. }
  76. }, func(pipe <-chan interface{}, cancel func(error)) {
  77. for item := range pipe {
  78. route := item.(rest.Route)
  79. s.Server.AddRoute(route)
  80. }
  81. })
  82. }
  83. func (s *Server) buildHandler(source grpcurl.DescriptorSource, resolver jsonpb.AnyResolver,
  84. cli zrpc.Client, m mapping) func(http.ResponseWriter, *http.Request) {
  85. return func(w http.ResponseWriter, r *http.Request) {
  86. handler := &grpcurl.DefaultEventHandler{
  87. Out: w,
  88. Formatter: grpcurl.NewJSONFormatter(true,
  89. grpcurl.AnyResolverFromDescriptorSource(source)),
  90. }
  91. parser, err := internal.NewRequestParser(r, resolver)
  92. if err != nil {
  93. httpx.Error(w, err)
  94. return
  95. }
  96. timeout := internal.GetTimeout(r.Header, s.timeout)
  97. ctx, can := context.WithTimeout(r.Context(), timeout)
  98. defer can()
  99. w.Header().Set(httpx.ContentType, httpx.JsonContentType)
  100. if err := grpcurl.InvokeRPC(ctx, source, cli.Conn(), m.RpcPath, internal.BuildHeaders(r.Header),
  101. handler, parser.Next); err != nil {
  102. httpx.Error(w, err)
  103. }
  104. }
  105. }
  106. func (s *Server) createDescriptorSource(cli zrpc.Client, up upstream) (grpcurl.DescriptorSource, error) {
  107. var source grpcurl.DescriptorSource
  108. var err error
  109. if len(up.ProtoSet) > 0 {
  110. source, err = grpcurl.DescriptorSourceFromProtoSets(up.ProtoSet)
  111. if err != nil {
  112. return nil, err
  113. }
  114. } else {
  115. refCli := grpc_reflection_v1alpha.NewServerReflectionClient(cli.Conn())
  116. client := grpcreflect.NewClient(context.Background(), refCli)
  117. source = grpcurl.DescriptorSourceFromServer(context.Background(), client)
  118. }
  119. return source, nil
  120. }