The Problem
Currently, we have to manually callc.Validate() in every handler:
- ❌ Repetitive code in every handler
- ❌ Easy to forget to validate
- ❌ Violates DRY (Don’t Repeat Yourself)
The Solution: Validation Middleware
How It Works
Implementation
1. Validation Middleware
2. Register Middleware in main.go
3. Simplified Handlers
Before (Manual Validation):How the Middleware Works Internally
Step-by-Step Execution
Context Wrapping Pattern
The Decorator Pattern
Advanced: Conditional Validation
Skip Validation for Certain Routes
Comparison: Manual vs Automatic
Manual Validation (Current)
Pros:- ✅ Explicit (you see what’s happening)
- ✅ Fine-grained control
- ❌ Repetitive code
- ❌ Easy to forget
- ❌ Violates DRY
Automatic Validation (Middleware)
Pros:- ✅ DRY (Don’t Repeat Yourself)
- ✅ Can’t forget to validate
- ✅ Cleaner handlers
- ⚠️ Less explicit (validation is “hidden”)
- ⚠️ Slightly harder to debug
When to Use Each Approach
Use Manual Validation When:
- You need fine-grained control
- You want explicit validation for clarity
- You have conditional validation logic
- You’re learning the framework
Use Automatic Validation When:
- You have many endpoints
- You want consistent validation across all routes
- You prefer DRY code
- You’re building a production API
Testing the Middleware
Test 1: Valid Request
Test 2: Invalid Email
Test 3: Missing Field
Alternative Approach: Generic Validator Function
If you don’t want middleware, you can create a helper function:- ✅ Explicit
- ✅ Reusable
- ✅ No middleware magic
- ⚠️ Still need to call it in every handler
Recommendation
-
Use Automatic Validation Middleware for most routes
- Cleaner code
- Consistent validation
- Less chance of forgetting
-
Keep Manual Validation for special cases
- File uploads
- Webhooks
- Complex multi-step forms
-
Document the behavior in API docs
- Developers should know validation happens automatically
Summary
Automatic Validation Middleware:- Wraps
echo.Contextwith a custom context - Overrides
Bind()to automatically callValidate() - Eliminates repetitive
c.Validate()calls - Makes handlers cleaner and more maintainable