36 lines
893 B
Go
36 lines
893 B
Go
|
|
package tenantctx
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
|
||
|
|
"google.golang.org/grpc"
|
||
|
|
"google.golang.org/grpc/metadata"
|
||
|
|
)
|
||
|
|
|
||
|
|
const headerKey = "x-tenant-id"
|
||
|
|
|
||
|
|
func InjectTenantId(ctx context.Context, tenantId string) context.Context {
|
||
|
|
return metadata.AppendToOutgoingContext(ctx, headerKey, tenantId)
|
||
|
|
}
|
||
|
|
|
||
|
|
func ExtractTenantId(ctx context.Context) string {
|
||
|
|
md, ok := metadata.FromIncomingContext(ctx)
|
||
|
|
if !ok {
|
||
|
|
return ""
|
||
|
|
}
|
||
|
|
vals := md.Get(headerKey)
|
||
|
|
if len(vals) == 0 {
|
||
|
|
return ""
|
||
|
|
}
|
||
|
|
return vals[0]
|
||
|
|
}
|
||
|
|
|
||
|
|
func UnaryClientInterceptor() grpc.UnaryClientInterceptor {
|
||
|
|
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
||
|
|
if tid, ok := ctx.Value("tenantId").(string); ok && tid != "" {
|
||
|
|
ctx = metadata.AppendToOutgoingContext(ctx, headerKey, tid)
|
||
|
|
}
|
||
|
|
return invoker(ctx, method, req, reply, cc, opts...)
|
||
|
|
}
|
||
|
|
}
|