create-schematic-gen-site/source/csgs/http.d

57 lines
1.8 KiB
D
Raw Normal View History

module csgs.http;
import handy_httpd;
import handy_httpd.handlers.path_delegating_handler;
import handy_httpd.handlers.file_resolving_handler;
import slf4d;
import std.path;
import csgs.extract;
void startServer() {
ServerConfig config = ServerConfig.defaultValues();
config.workerPoolSize = 3;
config.connectionQueueSize = 10;
config.port = 8100;
PathDelegatingHandler handler = new PathDelegatingHandler();
handler.addMapping("POST", "/extracts", &handleExtract);
handler.addMapping("GET", "/extracts/{extractId}", &getExtract);
handler.addMapping("POST", "/item-reports", &handleItemReport);
2023-07-23 15:40:07 +00:00
handler.addMapping("GET", "/status", (ref HttpRequestContext ctx) {
ctx.response.setStatus(HttpStatus.OK);
ctx.response.writeBodyString("online");
});
FileResolvingHandler fileHandler = new FileResolvingHandler("site", DirectoryResolutionStrategies.serveIndexFiles);
handler.addMapping("/**", fileHandler);
new HttpServer(handler, config).start();
}
private void handleExtract(ref HttpRequestContext ctx) {
import std.json;
MultipartFormData data = ctx.request.readBodyAsMultipartFormData();
if (!validateExtractRequest(data, ctx.response)) return;
string extractId = doExtract(data);
JSONValue result = JSONValue.emptyObject;
result.object["extractId"] = JSONValue(extractId);
ctx.response.writeBodyString(result.toJSON(), "application/json");
}
private void getExtract(ref HttpRequestContext ctx) {
string extractId = ctx.request.getPathParamAs!string("extractId");
const extractFile = buildPath(EXTRACTS_DIR, extractId ~ ".json");
fileResponse(ctx.response, extractFile, "application/json");
}
private void handleItemReport(ref HttpRequestContext ctx) {
import std.string : strip;
import std.stdio;
string itemName = ctx.request.readBodyAsString().strip();
File f = File("item-reports.txt", "a");
f.writeln(itemName);
f.close();
}