1 Star 1 Fork 0

Allen / go-scaffold

Create your Gitee Account
Explore and code with more than 5 million developers,Free private repositories !:)
Sign up
Clone or download
interceptors.go 2.09 KB
Copy Edit Raw Blame History
Allen authored 2020-08-18 20:54 . add tls config
package server
import (
"errors"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
)
// RecoveryHandlerFunc is a function that recovers from the panic `p` by returning an `error`.
type RecoveryHandlerFunc func(p interface{}) (err error)
// RecoveryHandlerFuncContext is a function that recovers from the panic `p` by returning an `error`.
// The context can be used to extract request scoped metadata and context values.
type RecoveryHandlerFuncContext func(ctx context.Context, p interface{}) (err error)
// UnaryServerInterceptor returns a new unary server interceptor for panic recovery.
func UnaryServerInterceptor(opts ...RecoveryOption) grpc.UnaryServerInterceptor {
o := evaluateOptions(opts)
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {
// recover panic
defer func() {
if r := recover(); r != nil {
switch t := r.(type) {
case string:
err = errors.New(t)
case error:
err = t
default:
err = errors.New("unknown error")
}
grpclog.Error(err.Error())
err = recoverFrom(ctx, r, o.recoveryHandlerFunc)
}
}()
return handler(ctx, req)
}
}
// StreamServerInterceptor returns a new streaming server interceptor for panic recovery.
func StreamServerInterceptor(opts ...RecoveryOption) grpc.StreamServerInterceptor {
o := evaluateOptions(opts)
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
// recover panic
defer func() {
if r := recover(); r != nil {
switch t := r.(type) {
case string:
err = errors.New(t)
case error:
err = t
default:
err = errors.New("unknown error")
}
grpclog.Error(err.Error())
err = recoverFrom(stream.Context(), r, o.recoveryHandlerFunc)
}
}()
return handler(srv, stream)
}
}
func recoverFrom(ctx context.Context, p interface{}, r RecoveryHandlerFuncContext) error {
if r == nil {
return grpc.Errorf(codes.Internal, "%s", p)
}
return r(ctx, p)
}

Comment ( 0 )

Sign in for post a comment

Go
1
https://gitee.com/zakums06/go-scaffold.git
git@gitee.com:zakums06/go-scaffold.git
zakums06
go-scaffold
go-scaffold
v0.1.11

Search