You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ntool-biz/core/i18n/grpc_interceptor.go

55 lines
1.8 KiB
Go

2 years ago
package i18n
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
// UnaryServerInterceptor grpc i18n 服务端拦截器
// 客户端将通过metadata传递其lang
// 将语言Key (lang) 从 grpc-metadata 中取出并注入到context中
// see github.com\zeromicro\go-zero\zrpc\server.go#AddUnaryInterceptors
// see google.golang.org\grpc\interceptor.go
func UnaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
var md metadata.MD
requestMetadata, ok := metadata.FromIncomingContext(ctx)
if ok {
md = requestMetadata.Copy()
} else {
md = metadata.MD{}
}
lngs := md.Get(KeyLang)
if len(lngs) > 0 {
lang := lngs[0]
if len(lang) > 0 {
ctx = context.WithValue(ctx, KeyLang, lang)
}
}
resp, err = handler(ctx, req)
return
}
}
// UnaryClientInterceptor i18n grpc 客户端拦截器
// 将context中的lang注入到metadata中传递给服务端
// see google.golang.org\grpc\interceptor.go
func UnaryClientInterceptor() grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
var md metadata.MD
requestMetadata, ok := metadata.FromOutgoingContext(ctx)
if ok {
md = requestMetadata.Copy()
} else {
md = metadata.MD{}
}
if lang, ok := ctx.Value(KeyLang).(string); ok && len(lang) > 0 {
md.Set(KeyLang, lang)
}
ctx = metadata.NewOutgoingContext(ctx, md)
return invoker(ctx, method, req, reply, cc, opts...)
}
}