2022-03-11 11:33:18 +00:00
|
|
|
package metadata
|
2022-03-10 11:46:36 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"google.golang.org/grpc"
|
|
|
|
"google.golang.org/grpc/metadata"
|
2022-03-11 11:33:18 +00:00
|
|
|
|
|
|
|
"go.linka.cloud/grpc/interceptors"
|
2022-03-10 11:46:36 +00:00
|
|
|
)
|
|
|
|
|
2022-03-11 11:33:18 +00:00
|
|
|
func NewInterceptors(pairs ...string) interceptors.Interceptors {
|
|
|
|
return mdInterceptors{pairs: pairs}
|
|
|
|
}
|
|
|
|
|
2022-03-10 11:46:36 +00:00
|
|
|
type mdInterceptors struct {
|
2022-03-11 11:33:18 +00:00
|
|
|
pairs []string
|
2022-03-10 11:46:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (i mdInterceptors) UnaryServerInterceptor() grpc.UnaryServerInterceptor {
|
|
|
|
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
|
2022-03-11 11:33:18 +00:00
|
|
|
if err := grpc.SetHeader(ctx, metadata.Pairs(i.pairs...)); err != nil {
|
2022-03-10 11:46:36 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return handler(ctx, req)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i mdInterceptors) StreamServerInterceptor() grpc.StreamServerInterceptor {
|
|
|
|
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
2022-03-11 11:33:18 +00:00
|
|
|
if err := grpc.SetHeader(ss.Context(), metadata.Pairs(i.pairs...)); err != nil {
|
2022-03-10 11:46:36 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
return handler(srv, ss)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i mdInterceptors) UnaryClientInterceptor() grpc.UnaryClientInterceptor {
|
|
|
|
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
2022-03-11 11:40:09 +00:00
|
|
|
ctx = metadata.NewOutgoingContext(ctx, metadata.Pairs(i.pairs...))
|
2022-03-10 11:46:36 +00:00
|
|
|
return invoker(ctx, method, req, reply, cc, opts...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i mdInterceptors) StreamClientInterceptor() grpc.StreamClientInterceptor {
|
|
|
|
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
|
2022-03-11 11:40:09 +00:00
|
|
|
ctx = metadata.NewOutgoingContext(ctx, metadata.Pairs(i.pairs...))
|
2022-03-10 11:46:36 +00:00
|
|
|
return streamer(ctx, desc, cc, method, opts...)
|
|
|
|
}
|
|
|
|
}
|