// Package handlers package handlers import ( "encoding/json" "log/slog" "net/http" ) const maxRequestBodySize = 1 << 20 // 1 MB // AppEnv is set at startup to control error detail exposure var AppEnv string // writeJSON writes a JSON response func writeJSON(w http.ResponseWriter, status int, v interface{}) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) json.NewEncoder(w).Encode(v) } // writeError writes an error response. // In production, internal server errors return a generic message. // In development, the actual error message is returned. func writeError(w http.ResponseWriter, status int, msg string, err error) { if err != nil { slog.Error("handler error", "status", status, "error", err) } if status == http.StatusInternalServerError && AppEnv == "production" { msg = "internal server error" } writeJSON(w, status, map[string]string{"error": msg}) } // writeValidationError writes a validation error response (422). // In production, hides internal field names and rules from the client. func writeValidationError(w http.ResponseWriter, err error) { details := err.Error() if AppEnv == "production" { slog.Error("validation error", "error", details) details = "validation failed" } writeJSON(w, http.StatusUnprocessableEntity, map[string]interface{}{ "error": "validation failed", "details": details, }) }