Created
August 7, 2022 21:33
-
-
Save alfonmga/ae304198a419245e471b49d24d40c7b0 to your computer and use it in GitHub Desktop.
Buf connect-go protoc-gen-validate interceptor by @akshayjshah
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var validatorInterceptor = connect.UnaryInterceptorFunc( | |
func(next connect.UnaryFunc) connect.UnaryFunc { | |
return connect.UnaryFunc(func(ctx context.Context, request connect.AnyRequest) (connect.AnyResponse, error) { | |
validator, ok := request.Any().(interface{ ValidateAll() error }) | |
if !ok { | |
// Handle this however you'd like; maybe return an error with | |
// CodeInternal if all your types should support validation? | |
return next(ctx, request) | |
} | |
if err := validator.ValidateAll(); err != nil { | |
// If the client needs very granular details about the error (maybe to | |
// highlight invalid data in some UI?), you can attach | |
// https://pkg.go.dev/google.golang.org/genproto/googleapis/rpc/errdetails#BadRequest | |
// as an error detail. I'm not super-familiar with protoc-gen-validate, | |
// so I'm not sure how to convert the ValidateAll error into a bunch of | |
// errdetail.BadRequest_FieldViolation messages. | |
return nil, connect.NewError(connect.CodeInvalidArgument, err) | |
} | |
return next(ctx, request) | |
}) | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example here by @utamori