Skip to content

Instantly share code, notes, and snippets.

@alfonmga
Created August 7, 2022 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alfonmga/ae304198a419245e471b49d24d40c7b0 to your computer and use it in GitHub Desktop.
Save alfonmga/ae304198a419245e471b49d24d40c7b0 to your computer and use it in GitHub Desktop.
Buf connect-go protoc-gen-validate interceptor by @akshayjshah
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)
})
}
)
@alfonmga
Copy link
Author

alfonmga commented Aug 16, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment