server.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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/codes"
  18. "google.golang.org/grpc/reflection/grpc_reflection_v1alpha"
  19. )
  20. type (
  21. // Server is a gateway server.
  22. Server struct {
  23. *rest.Server
  24. upstreams []Upstream
  25. timeout time.Duration
  26. processHeader func(http.Header) []string
  27. }
  28. // Option defines the method to customize Server.
  29. Option func(svr *Server)
  30. )
  31. // MustNewServer creates a new gateway server.
  32. func MustNewServer(c GatewayConf, opts ...Option) *Server {
  33. svr := &Server{
  34. Server: rest.MustNewServer(c.RestConf),
  35. upstreams: c.Upstreams,
  36. timeout: c.Timeout,
  37. }
  38. for _, opt := range opts {
  39. opt(svr)
  40. }
  41. return svr
  42. }
  43. // Start starts the gateway server.
  44. func (s *Server) Start() {
  45. logx.Must(s.build())
  46. s.Server.Start()
  47. }
  48. // Stop stops the gateway server.
  49. func (s *Server) Stop() {
  50. s.Server.Stop()
  51. }
  52. func (s *Server) build() error {
  53. if err := s.ensureUpstreamNames(); err != nil {
  54. return err
  55. }
  56. return mr.MapReduceVoid(func(source chan<- interface{}) {
  57. for _, up := range s.upstreams {
  58. source <- up
  59. }
  60. }, func(item interface{}, writer mr.Writer, cancel func(error)) {
  61. up := item.(Upstream)
  62. cli := zrpc.MustNewClient(up.Grpc)
  63. source, err := s.createDescriptorSource(cli, up)
  64. if err != nil {
  65. cancel(fmt.Errorf("%s: %w", up.Name, err))
  66. return
  67. }
  68. methods, err := internal.GetMethods(source)
  69. if err != nil {
  70. cancel(fmt.Errorf("%s: %w", up.Name, err))
  71. return
  72. }
  73. resolver := grpcurl.AnyResolverFromDescriptorSource(source)
  74. for _, m := range methods {
  75. if len(m.HttpMethod) > 0 && len(m.HttpPath) > 0 {
  76. writer.Write(rest.Route{
  77. Method: m.HttpMethod,
  78. Path: m.HttpPath,
  79. Handler: s.buildHandler(source, resolver, cli, m.RpcPath),
  80. })
  81. }
  82. }
  83. methodSet := make(map[string]struct{})
  84. for _, m := range methods {
  85. methodSet[m.RpcPath] = struct{}{}
  86. }
  87. for _, m := range up.Mappings {
  88. if _, ok := methodSet[m.RpcPath]; !ok {
  89. cancel(fmt.Errorf("%s: rpc method %s not found", up.Name, m.RpcPath))
  90. return
  91. }
  92. writer.Write(rest.Route{
  93. Method: strings.ToUpper(m.Method),
  94. Path: m.Path,
  95. Handler: s.buildHandler(source, resolver, cli, m.RpcPath),
  96. })
  97. }
  98. }, func(pipe <-chan interface{}, cancel func(error)) {
  99. for item := range pipe {
  100. route := item.(rest.Route)
  101. s.Server.AddRoute(route)
  102. }
  103. })
  104. }
  105. func (s *Server) buildHandler(source grpcurl.DescriptorSource, resolver jsonpb.AnyResolver,
  106. cli zrpc.Client, rpcPath string) func(http.ResponseWriter, *http.Request) {
  107. return func(w http.ResponseWriter, r *http.Request) {
  108. handler := &grpcurl.DefaultEventHandler{
  109. Out: w,
  110. Formatter: grpcurl.NewJSONFormatter(true,
  111. grpcurl.AnyResolverFromDescriptorSource(source)),
  112. }
  113. parser, err := internal.NewRequestParser(r, resolver)
  114. if err != nil {
  115. httpx.Error(w, err)
  116. return
  117. }
  118. timeout := internal.GetTimeout(r.Header, s.timeout)
  119. ctx, can := context.WithTimeout(r.Context(), timeout)
  120. defer can()
  121. w.Header().Set(httpx.ContentType, httpx.JsonContentType)
  122. if err := grpcurl.InvokeRPC(ctx, source, cli.Conn(), rpcPath, s.prepareMetadata(r.Header),
  123. handler, parser.Next); err != nil {
  124. httpx.Error(w, err)
  125. }
  126. st := handler.Status
  127. if st.Code() != codes.OK {
  128. httpx.Error(w, st.Err())
  129. }
  130. }
  131. }
  132. func (s *Server) createDescriptorSource(cli zrpc.Client, up Upstream) (grpcurl.DescriptorSource, error) {
  133. var source grpcurl.DescriptorSource
  134. var err error
  135. if len(up.ProtoSets) > 0 {
  136. source, err = grpcurl.DescriptorSourceFromProtoSets(up.ProtoSets...)
  137. if err != nil {
  138. return nil, err
  139. }
  140. } else {
  141. refCli := grpc_reflection_v1alpha.NewServerReflectionClient(cli.Conn())
  142. client := grpcreflect.NewClient(context.Background(), refCli)
  143. source = grpcurl.DescriptorSourceFromServer(context.Background(), client)
  144. }
  145. return source, nil
  146. }
  147. func (s *Server) ensureUpstreamNames() error {
  148. for _, up := range s.upstreams {
  149. target, err := up.Grpc.BuildTarget()
  150. if err != nil {
  151. return err
  152. }
  153. up.Name = target
  154. }
  155. return nil
  156. }
  157. func (s *Server) prepareMetadata(header http.Header) []string {
  158. vals := internal.ProcessHeaders(header)
  159. if s.processHeader != nil {
  160. vals = append(vals, s.processHeader(header)...)
  161. }
  162. return vals
  163. }
  164. // WithHeaderProcessor sets a processor to process request headers.
  165. // The returned headers are used as metadata to invoke the RPC.
  166. func WithHeaderProcessor(processHeader func(http.Header) []string) func(*Server) {
  167. return func(s *Server) {
  168. s.processHeader = processHeader
  169. }
  170. }