Files
files/internal/handler/helpers.go
2026-06-17 13:54:04 +03:00

28 lines
700 B
Go

package handler
import (
"encoding/json"
"log/slog"
"net/http"
)
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
func writeInternalError(w http.ResponseWriter, r *http.Request, err error, msg string) {
slog.Error("http error", "method", r.Method, "path", r.URL.Path, "err", err)
writeError(w, http.StatusInternalServerError, msg)
}
func decodeJSON(r *http.Request, v any) error {
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(v)
}