Overview
The validation middleware automatically validates incoming requests before they reach your handlers. It supports multiple validation methods including the validator interface, custom validation functions, and protovalidate for Protocol Buffers.Installation
Basic Usage
TheValidator function creates a validation middleware:
Server Example
Validation Methods
1. Validator Interface
Implement theValidate() method on your request types:
Usage Example
Validate() on any request that implements the interface.
2. Custom Validator Functions
Pass custom validation functions to the middleware:Usage Example
3. Protocol Buffers Validation
For Protocol Buffers, use protovalidate or protoc-gen-validate:Using buf protovalidate
Using Google AIP Field Behavior
Error Handling
Validation errors are returned as:- HTTP status:
400 Bad Request - gRPC code:
INVALID_ARGUMENT - Reason:
"VALIDATOR"
Error Response Example
Validation Order
The middleware validates in this order:- Built-in
Validate()method (if request implementsvalidatorinterface) - Custom validator functions (in the order provided)
Complete Example
Testing Validation
Advanced Validation
Conditional Validation
Cross-Field Validation
Using Third-Party Validators
go-playground/validator
Best Practices
Validate Early
Validate Early
Always place validation middleware early in the chain, after recovery but before business logic.
Keep Validation Simple
Keep Validation Simple
Validation should check format and constraints, not business logic. Use separate middleware for business rules.
Return Clear Error Messages
Return Clear Error Messages
Provide specific, actionable error messages that help users fix their requests.
Use protovalidate for Proto
Use protovalidate for Proto
For Protocol Buffers, use protovalidate to define validation rules in .proto files.
Test Validation Thoroughly
Test Validation Thoroughly
Write comprehensive tests for all validation rules including edge cases.
Don't Duplicate Validation
Don't Duplicate Validation
Implement validation once in the middleware, not in every handler.
Selective Validation
Apply validation to specific routes:Common Validation Rules
Here are common validation patterns:Source Reference
The validation middleware implementation can be found in:middleware/validate/validate.go:44- Validator middlewaremiddleware/validate/validate.go:10- ValidatorFunc typemiddleware/validate/validate.go:13- validator interfacecontrib/middleware/validate/validate.go:18- ProtoValidate middleware
Next Steps
Authentication
Add JWT authentication
Logging
Log validation failures