proxy: use grpc interfaces instead of *grpc.Server and *grpc.ClientConn, use Service and service Options

Signed-off-by: Adphi <philippe.adrien.nousse@gmail.com>
This commit is contained in:
2025-04-14 08:56:55 +02:00
parent 82e4d9a944
commit 8999dedd32
7 changed files with 182 additions and 230 deletions

View File

@ -8,26 +8,32 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"go.linka.cloud/grpc-toolkit/service"
)
// NewProxy sets up a simple proxy that forwards all requests to dst.
func NewProxy(dst *grpc.ClientConn, opts ...grpc.ServerOption) *grpc.Server {
opts = append(opts, DefaultProxyOpt(dst))
// New sets up a simple proxy that forwards all requests to dst.
func New(dst grpc.ClientConnInterface, opts ...service.Option) (service.Service, error) {
opts = append(opts, WithDefault(dst))
// Set up the proxy server and then serve from it like in step one.
return grpc.NewServer(opts...)
return service.New(opts...)
}
// DefaultProxyOpt returns an grpc.UnknownServiceHandler with a DefaultDirector.
func DefaultProxyOpt(cc *grpc.ClientConn) grpc.ServerOption {
return grpc.UnknownServiceHandler(TransparentHandler(DefaultDirector(cc)))
// WithDefault returns a grpc.UnknownServiceHandler with a DefaultDirector.
func WithDefault(cc grpc.ClientConnInterface) service.Option {
return service.WithGRPCServerOpts(grpc.UnknownServiceHandler(TransparentHandler(DefaultDirector(cc))))
}
// DefaultDirector returns a very simple forwarding StreamDirector that forwards all
// calls.
func DefaultDirector(cc *grpc.ClientConn) StreamDirector {
func DefaultDirector(cc grpc.ClientConnInterface) StreamDirector {
return func(ctx context.Context, fullMethodName string) (context.Context, grpc.ClientConnInterface, error) {
md, _ := metadata.FromIncomingContext(ctx)
ctx = metadata.NewOutgoingContext(ctx, md.Copy())
return ctx, cc, nil
}
}
func With(director StreamDirector) service.Option {
return service.WithGRPCServerOpts(grpc.UnknownServiceHandler(TransparentHandler(director)))
}