|
|
@@ -1,44 +1,45 @@
|
|
|
-// Package handlers
|
|
|
package handlers
|
|
|
|
|
|
import (
|
|
|
"encoding/json"
|
|
|
"log/slog"
|
|
|
"net/http"
|
|
|
+ "sync/atomic"
|
|
|
)
|
|
|
|
|
|
const maxRequestBodySize = 1 << 20 // 1 MB
|
|
|
|
|
|
-// AppEnv is set at startup to control error detail exposure
|
|
|
-var AppEnv string
|
|
|
+var isProd atomic.Bool
|
|
|
+
|
|
|
+func InitAppEnv(env string) {
|
|
|
+ isProd.Store(env == "production")
|
|
|
+}
|
|
|
+
|
|
|
+func ResetAppEnv() {
|
|
|
+ isProd.Store(false)
|
|
|
+}
|
|
|
|
|
|
-// 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" {
|
|
|
+ if status == http.StatusInternalServerError && isProd.Load() {
|
|
|
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" {
|
|
|
+ if isProd.Load() {
|
|
|
slog.Error("validation error", "error", details)
|
|
|
details = "validation failed"
|
|
|
}
|