package httpx import ( "context" "encoding/json" "errors" "net" "net/http" "strings" "github.com/jackc/pgx/v5/pgconn" "mtusi2026-messenger/internal/dto" ) func WriteJSON(w http.ResponseWriter, status int, body any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(body) } func WriteError(w http.ResponseWriter, status int, code dto.ErrorCode, message, requestID string) { WriteJSON(w, status, dto.ErrorResponse{ Error: dto.Error{ Code: code, Message: message, RequestID: requestID, }, }) } func WriteInternalError(w http.ResponseWriter, requestID string, err error) { if isUnavailable(err) { WriteError( w, http.StatusServiceUnavailable, dto.ErrorCodeUnavailable, "dependency unavailable", requestID, ) return } WriteError( w, http.StatusInternalServerError, dto.ErrorCodeInternalError, "internal server error", requestID, ) } func isUnavailable(err error) bool { if errors.Is(err, context.DeadlineExceeded) { return true } if _, ok := errors.AsType[net.Error](err); ok { return true } if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok { return strings.HasPrefix(pgErr.Code, "08") || pgErr.Code == "57P01" } return false }