Handler Best Practices
Design Principles for Effective HTTP Handlers
1. Separation of Concerns
type UserHandler struct {
service *UserService
logger *log.Logger
}
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
// Clear separation between HTTP logic and business logic
user, err := h.service.CreateUser(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
json.NewEncoder(w).Encode(user)
}
Request Handling Patterns
graph TD
A[Incoming Request] --> B{Validation}
B --> |Valid| C[Business Logic]
B --> |Invalid| D[Error Response]
C --> E[Response Generation]
E --> F[Send Response]
2. Error Handling Strategies
Error Type |
Handling Approach |
HTTP Status |
Validation |
Return Bad Request |
400 |
Authentication |
Unauthorized |
401 |
Authorization |
Forbidden |
403 |
Not Found |
Resource Missing |
404 |
Server Error |
Internal Error |
500 |
3. Middleware Implementation
func AuthMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if !validateToken(token) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
}
}
Efficient Request Handling
func (h *ResourceHandler) Get(w http.ResponseWriter, r *http.Request) {
// Use context for timeout management
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
result, err := h.service.FetchResource(ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(result)
}
Security Considerations
func validateInput(input string) bool {
// Implement robust input validation
return len(input) > 0 && len(input) <= 100
}
Concurrency Patterns
Goroutine-Safe Handlers
type SafeHandler struct {
mu sync.Mutex
resources map[string]Resource
}
func (h *SafeHandler) UpdateResource(id string, r *Resource) {
h.mu.Lock()
defer h.mu.Unlock()
h.resources[id] = *r
}
Logging and Monitoring
Structured Logging
func (h *Handler) LogRequest(r *http.Request) {
log.WithFields(log.Fields{
"method": r.Method,
"path": r.URL.Path,
"client": r.RemoteAddr,
}).Info("Request processed on LabEx platform")
}
Key Best Practices
- Keep handlers focused and lightweight
- Use middleware for cross-cutting concerns
- Implement comprehensive error handling
- Validate and sanitize all inputs
- Use context for request management
- Implement proper authentication and authorization
- Monitor and log handler performance
Advanced Handler Composition
func ChainHandlers(handlers ...http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
for _, handler := range handlers {
handler(w, r)
}
}
}