1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
| package main
import ( "context" "log" "time"
"google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" )
func loggingUnaryInterceptor( ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, ) (interface{}, error) { start := time.Now()
resp, err := handler(ctx, req)
duration := time.Since(start) statusCode := codes.OK if err != nil { statusCode = status.Code(err) } log.Printf("method=%s duration=%v status=%s error=%v", info.FullMethod, duration, statusCode, err)
return resp, err }
func authUnaryInterceptor( ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, ) (interface{}, error) { if info.FullMethod == "/grpc.health.v1.Health/Check" { return handler(ctx, req) }
md, ok := metadata.FromIncomingContext(ctx) if !ok { return nil, status.Error(codes.Unauthenticated, "missing metadata") }
tokens := md.Get("authorization") if len(tokens) == 0 { return nil, status.Error(codes.Unauthenticated, "missing authorization token") }
userID, err := validateToken(tokens[0]) if err != nil { return nil, status.Error(codes.Unauthenticated, "invalid token") }
newCtx := context.WithValue(ctx, "userID", userID) return handler(newCtx, req) }
func recoveryUnaryInterceptor( ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, ) (resp interface{}, err error) { defer func() { if r := recover(); r != nil { log.Printf("panic recovered in %s: %v", info.FullMethod, r) err = status.Errorf(codes.Internal, "internal server error") } }() return handler(ctx, req) }
func timeoutUnaryInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor { return func( ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption, ) error { ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() return invoker(ctx, method, req, reply, cc, opts...) } }
func retryUnaryInterceptor(maxRetries int) grpc.UnaryClientInterceptor { return func( ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption, ) error { var lastErr error for i := 0; i <= maxRetries; i++ { lastErr = invoker(ctx, method, req, reply, cc, opts...) if lastErr == nil { return nil }
code := status.Code(lastErr) if code != codes.Unavailable && code != codes.DeadlineExceeded { return lastErr }
backoff := time.Duration(1<<uint(i)) * 100 * time.Millisecond select { case <-ctx.Done(): return ctx.Err() case <-time.After(backoff): } } return lastErr } }
func validateToken(token string) (string, error) { if token == "valid-token" { return "user-123", nil } return "", status.Error(codes.Unauthenticated, "invalid token") }
|