github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/muxer/muxer.go (about) 1 // Package muxer provides proxy muxing 2 package muxer 3 4 import ( 5 "context" 6 "sync" 7 8 debug "github.com/tickoalcantara12/micro/v3/service/debug/handler" 9 "github.com/tickoalcantara12/micro/v3/service/proxy" 10 "github.com/tickoalcantara12/micro/v3/service/server" 11 "github.com/tickoalcantara12/micro/v3/service/server/mucp" 12 ) 13 14 // Server is a proxy muxer that incudes the use of the DefaultHandler 15 type Server struct { 16 // name of service 17 Name string 18 // Proxy handler 19 Proxy proxy.Proxy 20 // The default handler 21 Handler Handler 22 } 23 24 type Handler interface { 25 proxy.Proxy 26 NewHandler(interface{}, ...server.HandlerOption) server.Handler 27 Handle(server.Handler) error 28 } 29 30 var ( 31 once sync.Once 32 ) 33 34 func (s *Server) ProcessMessage(ctx context.Context, msg server.Message) error { 35 if msg.Topic() == s.Name { 36 return s.Handler.ProcessMessage(ctx, msg) 37 } 38 return s.Proxy.ProcessMessage(ctx, msg) 39 } 40 41 func (s *Server) ServeRequest(ctx context.Context, req server.Request, rsp server.Response) error { 42 if req.Service() == s.Name { 43 return s.Handler.ServeRequest(ctx, req, rsp) 44 } 45 return s.Proxy.ServeRequest(ctx, req, rsp) 46 } 47 48 func New(name string, p proxy.Proxy) *Server { 49 r := mucp.DefaultRouter 50 51 // only register this once 52 once.Do(func() { 53 r.Handle( 54 // inject the debug handler 55 r.NewHandler( 56 debug.NewHandler(), 57 server.InternalHandler(true), 58 ), 59 ) 60 }) 61 62 return &Server{ 63 Name: name, 64 Proxy: p, 65 Handler: r, 66 } 67 }