1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
auth.go 1.21 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-08-09 21:36 . rpc
package rpc
import (
"context"
"google.golang.org/grpc"
)
type AuthFunc func(ctx context.Context, req interface{}, fullMethodName string) (context.Context, error)
// ServiceAuthOverride allows a given gRPC service implementation to override the global `AuthFunc`.
//
// If a service implements the AuthFuncOverride method, it takes precedence over the `AuthFunc` method,
// and will be called instead of AuthFunc for all method invocations within that service.
type ServiceAuthOverride interface {
AuthFuncOverride(ctx context.Context, req interface{}, fullMethodName string) (context.Context, error)
}
// UnaryServerInterceptor returns a new unary server interceptors that performs per-request auth.
func UnaryServerInterceptor(authFunc AuthFunc) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
var newCtx context.Context
var err error
if overrideSrv, ok := info.Server.(ServiceAuthOverride); ok {
newCtx, err = overrideSrv.AuthFuncOverride(ctx, req, info.FullMethod)
} else {
newCtx, err = authFunc(ctx, req, info.FullMethod)
}
if err != nil {
return nil, err
}
return handler(newCtx, req)
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.11

搜索帮助