| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- package handlers
- import (
- "encoding/json"
- "log/slog"
- "net/http"
- "sync/atomic"
- )
- const maxRequestBodySize = 1 << 20 // 1 MB
- var isProd atomic.Bool
- func InitAppEnv(env string) {
- isProd.Store(env == "production")
- }
- func ResetAppEnv() {
- isProd.Store(false)
- }
- func writeJSON(w http.ResponseWriter, status int, v interface{}) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(status)
- json.NewEncoder(w).Encode(v)
- }
- 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 && isProd.Load() {
- msg = "internal server error"
- }
- writeJSON(w, status, map[string]string{"error": msg})
- }
- func writeValidationError(w http.ResponseWriter, err error) {
- details := err.Error()
- if isProd.Load() {
- slog.Error("validation error", "error", details)
- details = "validation failed"
- }
- writeJSON(w, http.StatusUnprocessableEntity, map[string]interface{}{
- "error": "validation failed",
- "details": details,
- })
- }
|