package com.hubilon.util; import com.hubilon.json.JsonWriter; import com.sun.net.httpserver.HttpExchange; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; public final class HttpResponses { private HttpResponses() { } public static void sendBytes(HttpExchange exchange, int statusCode, String contentType, byte[] payload) throws IOException { exchange.getResponseHeaders().set("Content-Type", contentType); exchange.getResponseHeaders().set("Cache-Control", "no-store"); exchange.sendResponseHeaders(statusCode, payload.length == 0 ? -1 : payload.length); if (payload.length > 0) { try (OutputStream os = exchange.getResponseBody()) { os.write(payload); } } else { exchange.getResponseBody().close(); } } public static void sendText(HttpExchange exchange, int statusCode, String contentType, String text) throws IOException { sendBytes(exchange, statusCode, contentType, text.getBytes(StandardCharsets.UTF_8)); } public static void sendJson(HttpExchange exchange, int statusCode, Object payload) throws IOException { sendText(exchange, statusCode, "application/json; charset=utf-8", JsonWriter.write(payload)); } }