2019-08-13 15:21:51 +01:00
|
|
|
// Package mux provides proxy muxing
|
|
|
|
package mux
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"sync"
|
|
|
|
|
2020-07-27 13:22:00 +01:00
|
|
|
"github.com/micro/go-micro/v3/client/grpc"
|
|
|
|
"github.com/micro/go-micro/v3/debug/service/handler"
|
|
|
|
"github.com/micro/go-micro/v3/proxy"
|
|
|
|
"github.com/micro/go-micro/v3/server"
|
|
|
|
"github.com/micro/go-micro/v3/server/mucp"
|
2019-08-13 15:21:51 +01:00
|
|
|
)
|
|
|
|
|
2019-08-15 08:47:32 +01:00
|
|
|
// Server is a proxy muxer that incudes the use of the DefaultHandler
|
2019-08-13 15:21:51 +01:00
|
|
|
type Server struct {
|
|
|
|
// name of service
|
|
|
|
Name string
|
|
|
|
// Proxy handler
|
|
|
|
Proxy proxy.Proxy
|
2020-07-27 13:22:00 +01:00
|
|
|
// The default handler
|
|
|
|
Handler Handler
|
|
|
|
}
|
|
|
|
|
|
|
|
type Handler interface {
|
|
|
|
proxy.Proxy
|
|
|
|
NewHandler(interface{}, ...server.HandlerOption) server.Handler
|
|
|
|
Handle(server.Handler) error
|
2019-08-13 15:21:51 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
once sync.Once
|
|
|
|
)
|
|
|
|
|
2019-11-25 16:31:43 +00:00
|
|
|
func (s *Server) ProcessMessage(ctx context.Context, msg server.Message) error {
|
|
|
|
if msg.Topic() == s.Name {
|
2020-07-27 13:22:00 +01:00
|
|
|
return s.Handler.ProcessMessage(ctx, msg)
|
2019-11-25 16:31:43 +00:00
|
|
|
}
|
|
|
|
return s.Proxy.ProcessMessage(ctx, msg)
|
|
|
|
}
|
|
|
|
|
2019-08-13 15:21:51 +01:00
|
|
|
func (s *Server) ServeRequest(ctx context.Context, req server.Request, rsp server.Response) error {
|
|
|
|
if req.Service() == s.Name {
|
2020-07-27 13:22:00 +01:00
|
|
|
return s.Handler.ServeRequest(ctx, req, rsp)
|
2019-08-13 15:21:51 +01:00
|
|
|
}
|
|
|
|
return s.Proxy.ServeRequest(ctx, req, rsp)
|
|
|
|
}
|
|
|
|
|
|
|
|
func New(name string, p proxy.Proxy) *Server {
|
2020-07-27 13:22:00 +01:00
|
|
|
r := mucp.DefaultRouter
|
|
|
|
|
2019-08-13 15:21:51 +01:00
|
|
|
// only register this once
|
|
|
|
once.Do(func() {
|
2020-07-27 13:22:00 +01:00
|
|
|
r.Handle(
|
2020-01-29 22:31:57 +00:00
|
|
|
// inject the debug handler
|
2020-07-27 13:22:00 +01:00
|
|
|
r.NewHandler(
|
|
|
|
handler.NewHandler(grpc.NewClient()),
|
2019-12-02 14:55:35 +00:00
|
|
|
server.InternalHandler(true),
|
|
|
|
),
|
2019-08-13 15:21:51 +01:00
|
|
|
)
|
|
|
|
})
|
|
|
|
|
|
|
|
return &Server{
|
2020-07-27 13:22:00 +01:00
|
|
|
Name: name,
|
|
|
|
Proxy: p,
|
|
|
|
Handler: r,
|
2019-08-13 15:21:51 +01:00
|
|
|
}
|
|
|
|
}
|