mirror of
https://github.com/linka-cloud/grpc.git
synced 2025-06-22 01:02:29 +00:00
client: add interceptors option
This commit is contained in:
@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials"
|
||||
"google.golang.org/grpc/resolver"
|
||||
@ -36,6 +37,12 @@ func New(opts ...Option) (Client, error) {
|
||||
if !c.opts.secure {
|
||||
c.opts.dialOptions = append(c.opts.dialOptions, grpc.WithInsecure())
|
||||
}
|
||||
if len(c.opts.unaryInterceptors) > 0 {
|
||||
c.opts.dialOptions = append(c.opts.dialOptions, grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(c.opts.unaryInterceptors...)))
|
||||
}
|
||||
if len(c.opts.streamInterceptors) > 0 {
|
||||
c.opts.dialOptions = append(c.opts.dialOptions, grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(c.opts.streamInterceptors...)))
|
||||
}
|
||||
if c.opts.addr == "" {
|
||||
c.addr = fmt.Sprintf("%s:///%s", c.opts.registry.String(), c.opts.name)
|
||||
} else if strings.HasPrefix(c.opts.addr, "tcp://"){
|
||||
|
@ -5,6 +5,7 @@ import (
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"go.linka.cloud/grpc/interceptors"
|
||||
"go.linka.cloud/grpc/registry"
|
||||
)
|
||||
|
||||
@ -60,6 +61,27 @@ func WithDialOptions(opts ...grpc.DialOption) Option {
|
||||
}
|
||||
}
|
||||
|
||||
func WithInterceptors(i ...interceptors.ClientInterceptors) Option {
|
||||
return func(o *options) {
|
||||
for _, v := range i {
|
||||
o.unaryInterceptors = append(o.unaryInterceptors, v.UnaryClientInterceptor())
|
||||
o.streamInterceptors = append(o.streamInterceptors, v.StreamClientInterceptor())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func WithUnaryInterceptors(i ...grpc.UnaryClientInterceptor) Option {
|
||||
return func(o *options) {
|
||||
o.unaryInterceptors = append(o.unaryInterceptors, i...)
|
||||
}
|
||||
}
|
||||
|
||||
func WithStreamInterceptors(i ...grpc.StreamClientInterceptor) Option {
|
||||
return func(o *options) {
|
||||
o.streamInterceptors = append(o.streamInterceptors, i...)
|
||||
}
|
||||
}
|
||||
|
||||
type options struct {
|
||||
registry registry.Registry
|
||||
name string
|
||||
@ -68,6 +90,9 @@ type options struct {
|
||||
tlsConfig *tls.Config
|
||||
secure bool
|
||||
dialOptions []grpc.DialOption
|
||||
|
||||
unaryInterceptors []grpc.UnaryClientInterceptor
|
||||
streamInterceptors []grpc.StreamClientInterceptor
|
||||
}
|
||||
|
||||
func (o *options) Name() string {
|
||||
|
Reference in New Issue
Block a user