4528e04bad
Implemented 5 additional architectural improvements: 1. Response Types (types.go) - APIResponse with Success, Data, Error, Meta fields - ErrorInfo with Code, Message, Field, Details - MetaInfo with Timestamp, Version, RequestID - SuccessResponse() and NewErrorResponse() helpers - HealthCheckResponse for health endpoint - Consistent JSON API responses 2. Validation Tags (types.go) - Added struct tags to LanguageRequest - Added struct tags to PDFExportRequest - Declarative validation rules (oneof, required) - Self-documenting validation constraints - Ready for go-playground/validator integration 3. Context Helper Functions (middleware/preferences.go) - GetLanguage(), GetCVLength(), GetCVIcons(), GetCVTheme(), GetColorTheme() - IsLongCV(), IsShortCV() boolean helpers - ShowIcons(), HideIcons() boolean helpers - IsCleanTheme(), IsDefaultTheme() boolean helpers - IsDarkMode(), IsLightMode() boolean helpers - 13 new convenience functions for cleaner code 4. Typed Errors (errors.go) - ErrorCode constants for all error types - DomainError with Code, Message, Err, StatusCode, Field - Unwrap() support for error chains - WithError() and WithField() fluent builders - InvalidLanguageError(), InvalidLengthError(), etc. - PDFGenerationError(), MethodNotAllowedError(), RateLimitError() - 13 error codes, domain-specific constructors 5. Benchmark Tests - handlers/benchmarks_test.go (11 benchmarks) - middleware/benchmarks_test.go (12 benchmarks) - Sequential benchmarks for handlers, middleware, request parsing - Parallel benchmarks for concurrent load testing - Response creation benchmarks - Helper function benchmarks Benefits: - Type Safety: Validation tags and structured types - Developer Experience: 13 context helpers reduce boilerplate - Error Handling: Domain-specific errors with codes - Performance Monitoring: 23 benchmarks for regression detection - API Consistency: Standardized response formats - Maintainability: Self-documenting validation and errors Testing: - All unit tests pass - All benchmarks working - Build succeeds - No breaking changes
278 lines
7.0 KiB
Go
278 lines
7.0 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
// ErrorResponse represents a structured error response
|
|
type ErrorResponse struct {
|
|
Error string `json:"error"`
|
|
Message string `json:"message,omitempty"`
|
|
Code int `json:"code"`
|
|
}
|
|
|
|
// AppError represents an application error with context
|
|
type AppError struct {
|
|
Err error
|
|
Message string
|
|
StatusCode int
|
|
Internal bool // If true, don't expose details to client
|
|
}
|
|
|
|
// Error implements the error interface
|
|
func (e *AppError) Error() string {
|
|
if e.Err != nil {
|
|
return e.Err.Error()
|
|
}
|
|
return e.Message
|
|
}
|
|
|
|
// NewAppError creates a new application error
|
|
func NewAppError(err error, message string, statusCode int, internal bool) *AppError {
|
|
return &AppError{
|
|
Err: err,
|
|
Message: message,
|
|
StatusCode: statusCode,
|
|
Internal: internal,
|
|
}
|
|
}
|
|
|
|
// HandleError handles errors consistently across the application
|
|
func HandleError(w http.ResponseWriter, r *http.Request, err error) {
|
|
var appErr *AppError
|
|
|
|
// Check if it's an AppError
|
|
switch e := err.(type) {
|
|
case *AppError:
|
|
appErr = e
|
|
default:
|
|
// Unknown error - treat as internal server error
|
|
appErr = NewAppError(err, "Internal Server Error", http.StatusInternalServerError, true)
|
|
}
|
|
|
|
// Log the error
|
|
if appErr.Internal {
|
|
log.Printf("ERROR [%s %s]: %v", r.Method, r.URL.Path, appErr.Err)
|
|
} else {
|
|
log.Printf("CLIENT ERROR [%s %s]: %s (status: %d)", r.Method, r.URL.Path, appErr.Message, appErr.StatusCode)
|
|
}
|
|
|
|
// Determine response based on Accept header
|
|
accept := r.Header.Get("Accept")
|
|
isJSON := accept == "application/json"
|
|
isHTMX := r.Header.Get("HX-Request") != ""
|
|
|
|
if isJSON {
|
|
// JSON response
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(appErr.StatusCode)
|
|
|
|
response := ErrorResponse{
|
|
Error: http.StatusText(appErr.StatusCode),
|
|
Code: appErr.StatusCode,
|
|
}
|
|
|
|
// Only include message if not internal
|
|
if !appErr.Internal {
|
|
response.Message = appErr.Message
|
|
}
|
|
|
|
if err := json.NewEncoder(w).Encode(response); err != nil {
|
|
log.Printf("ERROR encoding JSON response: %v", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
if isHTMX {
|
|
// HTMX response - return simple HTML fragment
|
|
w.Header().Set("Content-Type", "text/html")
|
|
w.WriteHeader(appErr.StatusCode)
|
|
|
|
message := appErr.Message
|
|
if appErr.Internal {
|
|
message = "An error occurred. Please try again later."
|
|
}
|
|
|
|
if _, err := w.Write([]byte("<div class='error'>" + message + "</div>")); err != nil {
|
|
log.Printf("ERROR writing HTMX error response: %v", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
// Standard HTTP error response
|
|
message := appErr.Message
|
|
if appErr.Internal {
|
|
message = "Internal Server Error"
|
|
}
|
|
|
|
http.Error(w, message, appErr.StatusCode)
|
|
}
|
|
|
|
// Common error constructors
|
|
|
|
func NotFoundError(message string) *AppError {
|
|
return NewAppError(nil, message, http.StatusNotFound, false)
|
|
}
|
|
|
|
func BadRequestError(message string) *AppError {
|
|
return NewAppError(nil, message, http.StatusBadRequest, false)
|
|
}
|
|
|
|
func InternalError(err error) *AppError {
|
|
return NewAppError(err, "Internal Server Error", http.StatusInternalServerError, true)
|
|
}
|
|
|
|
func TemplateError(err error, templateName string) *AppError {
|
|
return NewAppError(
|
|
err,
|
|
"Error rendering template: "+templateName,
|
|
http.StatusInternalServerError,
|
|
true,
|
|
)
|
|
}
|
|
|
|
func DataLoadError(err error, dataType string) *AppError {
|
|
return NewAppError(
|
|
err,
|
|
"Error loading "+dataType+" data",
|
|
http.StatusInternalServerError,
|
|
true,
|
|
)
|
|
}
|
|
|
|
// ==============================================================================
|
|
// TYPED ERRORS
|
|
// Domain-specific error types for better error handling
|
|
// ==============================================================================
|
|
|
|
// ErrorCode represents a specific error condition
|
|
type ErrorCode string
|
|
|
|
const (
|
|
ErrCodeInvalidLanguage ErrorCode = "INVALID_LANGUAGE"
|
|
ErrCodeInvalidLength ErrorCode = "INVALID_LENGTH"
|
|
ErrCodeInvalidIcons ErrorCode = "INVALID_ICONS"
|
|
ErrCodeInvalidTheme ErrorCode = "INVALID_THEME"
|
|
ErrCodeInvalidVersion ErrorCode = "INVALID_VERSION"
|
|
ErrCodeTemplateNotFound ErrorCode = "TEMPLATE_NOT_FOUND"
|
|
ErrCodeTemplateRender ErrorCode = "TEMPLATE_RENDER"
|
|
ErrCodeDataLoad ErrorCode = "DATA_LOAD"
|
|
ErrCodePDFGeneration ErrorCode = "PDF_GENERATION"
|
|
ErrCodeMethodNotAllowed ErrorCode = "METHOD_NOT_ALLOWED"
|
|
ErrCodeUnauthorized ErrorCode = "UNAUTHORIZED"
|
|
ErrCodeForbidden ErrorCode = "FORBIDDEN"
|
|
ErrCodeRateLimitExceeded ErrorCode = "RATE_LIMIT_EXCEEDED"
|
|
)
|
|
|
|
// DomainError represents a domain-specific error
|
|
type DomainError struct {
|
|
Code ErrorCode
|
|
Message string
|
|
Err error
|
|
StatusCode int
|
|
Field string // Optional field that caused the error
|
|
}
|
|
|
|
// Error implements the error interface
|
|
func (e *DomainError) Error() string {
|
|
if e.Err != nil {
|
|
return fmt.Sprintf("%s: %v", e.Code, e.Err)
|
|
}
|
|
return fmt.Sprintf("%s: %s", e.Code, e.Message)
|
|
}
|
|
|
|
// Unwrap returns the underlying error
|
|
func (e *DomainError) Unwrap() error {
|
|
return e.Err
|
|
}
|
|
|
|
// NewDomainError creates a new domain error
|
|
func NewDomainError(code ErrorCode, message string, statusCode int) *DomainError {
|
|
return &DomainError{
|
|
Code: code,
|
|
Message: message,
|
|
StatusCode: statusCode,
|
|
}
|
|
}
|
|
|
|
// WithError adds an underlying error
|
|
func (e *DomainError) WithError(err error) *DomainError {
|
|
e.Err = err
|
|
return e
|
|
}
|
|
|
|
// WithField adds field information
|
|
func (e *DomainError) WithField(field string) *DomainError {
|
|
e.Field = field
|
|
return e
|
|
}
|
|
|
|
// Common domain error constructors
|
|
|
|
func InvalidLanguageError(lang string) *DomainError {
|
|
return NewDomainError(
|
|
ErrCodeInvalidLanguage,
|
|
fmt.Sprintf("Unsupported language: %s (use 'en' or 'es')", lang),
|
|
http.StatusBadRequest,
|
|
).WithField("lang")
|
|
}
|
|
|
|
func InvalidLengthError(length string) *DomainError {
|
|
return NewDomainError(
|
|
ErrCodeInvalidLength,
|
|
fmt.Sprintf("Unsupported length: %s (use 'short' or 'long')", length),
|
|
http.StatusBadRequest,
|
|
).WithField("length")
|
|
}
|
|
|
|
func InvalidIconsError(icons string) *DomainError {
|
|
return NewDomainError(
|
|
ErrCodeInvalidIcons,
|
|
fmt.Sprintf("Unsupported icons option: %s (use 'show' or 'hide')", icons),
|
|
http.StatusBadRequest,
|
|
).WithField("icons")
|
|
}
|
|
|
|
func InvalidThemeError(theme string) *DomainError {
|
|
return NewDomainError(
|
|
ErrCodeInvalidTheme,
|
|
fmt.Sprintf("Unsupported theme: %s (use 'default' or 'clean')", theme),
|
|
http.StatusBadRequest,
|
|
).WithField("theme")
|
|
}
|
|
|
|
func InvalidVersionError(version string) *DomainError {
|
|
return NewDomainError(
|
|
ErrCodeInvalidVersion,
|
|
fmt.Sprintf("Unsupported version: %s (use 'with_skills' or 'clean')", version),
|
|
http.StatusBadRequest,
|
|
).WithField("version")
|
|
}
|
|
|
|
func PDFGenerationError(err error) *DomainError {
|
|
return NewDomainError(
|
|
ErrCodePDFGeneration,
|
|
"Failed to generate PDF",
|
|
http.StatusInternalServerError,
|
|
).WithError(err)
|
|
}
|
|
|
|
func MethodNotAllowedError(method string) *DomainError {
|
|
return NewDomainError(
|
|
ErrCodeMethodNotAllowed,
|
|
fmt.Sprintf("Method %s not allowed", method),
|
|
http.StatusMethodNotAllowed,
|
|
)
|
|
}
|
|
|
|
func RateLimitError() *DomainError {
|
|
return NewDomainError(
|
|
ErrCodeRateLimitExceeded,
|
|
"Rate limit exceeded. Please try again later.",
|
|
http.StatusTooManyRequests,
|
|
)
|
|
}
|