77 lines
2.0 KiB
D
77 lines
2.0 KiB
D
import handy_httpd;
|
|
import handy_httpd.handlers.path_handler;
|
|
import handy_httpd.components.optional;
|
|
|
|
import std.json;
|
|
import std.stdio;
|
|
import core.sync.mutex;
|
|
|
|
import server_protocol;
|
|
|
|
__gshared JSONValue latestServerData = JSONValue.emptyArray;
|
|
__gshared Mutex dataMutex;
|
|
__gshared string clientKey;
|
|
__gshared string serverKey;
|
|
|
|
void main(string[] args) {
|
|
clientKey = args[1];
|
|
serverKey = args[2];
|
|
|
|
dataMutex = new Mutex();
|
|
|
|
PathHandler handler = new PathHandler();
|
|
handler.addMapping(Method.GET, "/servers", &listServers);
|
|
handler.addMapping(Method.POST, "/servers", &postServerStatus);
|
|
handler.addMapping(Method.POST, "/servers/:name/requests", &requestServerStartup);
|
|
|
|
ServerConfig config;
|
|
config.connectionQueueSize = 20;
|
|
config.receiveBufferSize = 4096;
|
|
config.workerPoolSize = 3;
|
|
HttpServer server = new HttpServer(handler, config);
|
|
server.start();
|
|
}
|
|
|
|
void listServers(ref HttpRequestContext ctx) {
|
|
dataMutex.lock();
|
|
ctx.response.writeBodyString(latestServerData.toJSON(), "application/json");
|
|
dataMutex.unlock();
|
|
}
|
|
|
|
void postServerStatus(ref HttpRequestContext ctx) {
|
|
Optional!string key = ctx.request.headers.getFirst("X-Server-Key");
|
|
if (!key || key.value != serverKey) {
|
|
ctx.response.status = HttpStatus.UNAUTHORIZED;
|
|
return;
|
|
}
|
|
|
|
JSONValue data = ctx.request.readBodyAsJson();
|
|
dataMutex.lock();
|
|
latestServerData = data;
|
|
writeln("Set server status to ", data.toJSON());
|
|
dataMutex.unlock();
|
|
}
|
|
|
|
void requestServerStartup(ref HttpRequestContext ctx) {
|
|
Optional!string key = ctx.request.headers.getFirst("X-Client-Key");
|
|
if (!key || key.value != clientKey) {
|
|
ctx.response.status = HttpStatus.UNAUTHORIZED;
|
|
return;
|
|
}
|
|
|
|
string serverName = ctx.request.getPathParamAs!string("name");
|
|
writeln(serverName);
|
|
dataMutex.lock();
|
|
scope(exit) {
|
|
dataMutex.unlock();
|
|
}
|
|
foreach (JSONValue serverNode; latestServerData.array) {
|
|
if (serverNode.object["name"].str == serverName) {
|
|
writeln("Found match!");
|
|
serverNode.object["requested"] = JSONValue(true);
|
|
return;
|
|
}
|
|
}
|
|
ctx.response.status = HttpStatus.NOT_FOUND;
|
|
}
|