middleware

package
v1.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 30, 2022 License: MIT Imports: 14 Imported by: 0

README

middleware

使用示例

jwt
func getServerOptions() []grpc.ServerOption {
	var options []grpc.ServerOption

	// token鉴权
	options = append(options, grpc.UnaryInterceptor(middleware.UnaryServerJwtAuth()))

	return options
}

func main() {
	fmt.Println("start rpc server", grpcAddr)
	middleware.AddSkipMethods("/proto.Account/Register") // 添加忽略token验证的方法,从pb文件的fullMethodName

	listen, err := net.Listen("tcp", grpcAddr)
	if err != nil {
		panic(err)
	}

	server := grpc.NewServer(getServerOptions()...)

    // ......
}

logging
var logger *zap.Logger

func getServerOptions() []grpc.ServerOption {
	var options []grpc.ServerOption

	// 日志设置,默认打印客户端断开连接信息,示例 https://pkg.go.dev/github.com/grpc-ecosystem/go-grpc-middleware/logging/zap
	//middleware.AddLoggingFields(map[string]interface{}{"hello": "world"}) // 添加打印自定义字段
	//middleware.AddSkipLoggingMethods("/proto.Greeter/SayHello") // 跳过打印调用的方法
	options = append(options, grpc_middleware.WithUnaryServerChain(
		middleware.UnaryServerCtxTags(),
		middleware.UnaryServerZapLogging(logger),
	))

	return options
}

func main() {
	logger, _ = zap.NewProduction()

	// 创建grpc server对象,拦截器可以在这里注入
	server := grpc.NewServer(getServerOptions()...)

	// ......
}

recovery
func getServerOptions() []grpc.ServerOption {
	var options []grpc.ServerOption

	recoveryOption := grpc_middleware.WithUnaryServerChain(
		middleware.UnaryServerRecovery(),
	)
	options = append(options, recoveryOption)

	return options
}

func main() {
	logger, _ = zap.NewProduction()

	// 创建grpc server对象,拦截器可以在这里注入
	server := grpc.NewServer(getServerOptions()...)

	// ......
}

retry
func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// 禁用tls
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	// 重试
	option := grpc.WithUnaryInterceptor(
		grpc_middleware.ChainUnaryClient(
			middleware.UnaryClientRetry(
                //middleware.WithRetryTimes(5), // 修改默认重试次数,默认3次
                //middleware.WithRetryInterval(100*time.Millisecond), // 修改默认重试时间间隔,默认50毫秒
                //middleware.WithRetryErrCodes(), // 添加触发重试错误码,默认codes.Internal, codes.DeadlineExceeded, codes.Unavailable
			),
		),
	)
	options = append(options, option)

	return options
}

func main() {
	conn, _ := grpc.Dial("127.0.0.1:8080", getDialOptions()...)
	client := pb.NewGreeterClient(conn)

	// ......
}

timeout
func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// 禁止tls加密
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	// 超时拦截器
	option := grpc.WithUnaryInterceptor(
		grpc_middleware.ChainUnaryClient(
			middleware.ContextTimeout(),
		),
	)
	options = append(options, option)

	return options
}

func main() {
	conn, _ := grpc.Dial("127.0.0.1:8080", getDialOptions()...)

    // ......
}

tracing
// 初始化trace
func InitTrace(serviceName string) {
	exporter, err := tracer.NewJaegerAgentExporter("192.168.3.37", "6831")
	if err != nil {
		panic(err)
	}

	resource := tracer.NewResource(
		tracer.WithServiceName(serviceName),
		tracer.WithEnvironment("dev"),
		tracer.WithServiceVersion("demo"),
	)

	tracer.Init(exporter, resource) // 默认采集全部
}

// 在客户端设置链路跟踪
func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// 禁用tls加密
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	// tracing跟踪
	options = append(options, grpc.WithUnaryInterceptor(
		middleware.UnaryClientTracing(),
	))

	return options
}

// 在服务端设置链路跟踪
func getServerOptions() []grpc.ServerOption {
	var options []grpc.ServerOption

	// 链路跟踪拦截器
	options = append(options, grpc.UnaryInterceptor(
		middleware.UnaryServerTracing(),
	))

	return options
}

// 如果有需要,可以在程序创建一个span
func SpanDemo(serviceName string, spanName string, ctx context.Context) {
	_, span := otel.Tracer(serviceName).Start(
		ctx, spanName,
		trace.WithAttributes(attribute.String(spanName, time.Now().String())), // 自定义属性
	)
	defer span.End()

	// ......
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddLoggingFields

func AddLoggingFields(kvs map[string]interface{})

AddLoggingFields 添加跳过认证方法,在服务初始化时设置

func AddSkipLoggingMethods

func AddSkipLoggingMethods(methodNames ...string)

AddSkipLoggingMethods 添加跳过打印日志方法,在服务初始化时设置

func AddSkipMethods

func AddSkipMethods(routers ...string)

AddSkipMethods 添加跳过认证方法,在服务初始化时设置

func ContextTimeout

func ContextTimeout() grpc.UnaryClientInterceptor

ContextTimeout 一元调用超时中间件

func GetAuthScheme

func GetAuthScheme() string

GetAuthScheme 获取Scheme

func JwtVerify

func JwtVerify(ctx context.Context) (context.Context, error)

JwtVerify 从context获取token验证是否合法

func StreamClientTracing

func StreamClientTracing() grpc.StreamClientInterceptor

StreamClientTracing 客户端流链路跟踪

func StreamContextTimeout

func StreamContextTimeout() grpc.StreamClientInterceptor

StreamContextTimeout 流式调用超时中间件

func StreamServerTracing

func StreamServerTracing() grpc.StreamServerInterceptor

StreamServerTracing 服务端流链路跟踪

func UnaryClientRetry

func UnaryClientRetry(opts ...Option) grpc.UnaryClientInterceptor

UnaryClientRetry 重试

func UnaryClientTracing

func UnaryClientTracing() grpc.UnaryClientInterceptor

UnaryClientTracing 客户端一元链路跟踪

func UnaryServerCtxTags

func UnaryServerCtxTags() grpc.UnaryServerInterceptor

UnaryServerCtxTags field extractor logging

func UnaryServerJwtAuth

func UnaryServerJwtAuth() grpc.UnaryServerInterceptor

UnaryServerJwtAuth jwt认证拦截器

func UnaryServerRecovery

func UnaryServerRecovery() grpc.UnaryServerInterceptor

UnaryServerRecovery 发生panic时恢复

func UnaryServerTracing

func UnaryServerTracing() grpc.UnaryServerInterceptor

UnaryServerTracing 服务端一元链路跟踪

func UnaryServerZapLogging

func UnaryServerZapLogging(logger *zap.Logger) grpc.UnaryServerInterceptor

UnaryServerZapLogging 日志打印拦截器

Types

type Option

type Option func(*options)

Option set the retry options.

func WithRetryErrCodes

func WithRetryErrCodes(errCodes ...codes.Code) Option

WithRetryErrCodes 设置触发重试错误码

func WithRetryInterval

func WithRetryInterval(t time.Duration) Option

WithRetryInterval 设置重试时间间隔,范围1毫秒到10秒

func WithRetryTimes

func WithRetryTimes(n uint) Option

WithRetryTimes 设置重试次数,最大10次

type SkipAuthMethod

type SkipAuthMethod struct{}

SkipAuthMethod 跳过认证,嵌入服务

func (*SkipAuthMethod) AuthFuncOverride

func (s *SkipAuthMethod) AuthFuncOverride(ctx context.Context, fullMethodName string) (context.Context, error)

AuthFuncOverride 重写认证方法

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL