service-ping/source/app.d

39 lines
1.2 KiB
D
Raw Normal View History

2024-03-22 20:17:57 +00:00
import handy_httpd;
import std.conv : to;
void main(string[] args) {
ServerConfig cfg;
cfg.workerPoolSize = 5;
cfg.defaultHeaders["Access-Control-Allow-Origin"] = "*";
if (args.length >= 2) cfg.hostname = args[1];
if (args.length >= 3) cfg.port = args[2].to!ushort;
new HttpServer(new RequestHandler(), cfg).start();
}
class RequestHandler : HttpRequestHandler {
void handle(ref HttpRequestContext ctx) {
auto maybeParam = ctx.request.queryParams.getFirst("address");
if (!maybeParam) {
ctx.response.status = HttpStatus.BAD_REQUEST;
ctx.response.writeBodyString("Required query parameter \"address\" is missing.");
return;
}
string address = maybeParam.value;
bool pingSuccessful = doPing(address);
import std.json;
JSONValue responseBody = JSONValue.emptyObject;
responseBody.object["success"] = JSONValue(pingSuccessful);
ctx.response.writeBodyString(responseBody.toJSON, "application/json");
}
bool doPing(string address) {
import std.process;
auto result = execute(["ping", address, "-c", "1", "-W", "1"]);
const int status = result.status;
return status == 0;
}
}