Newer
Older
dub_jkp / test / test_registry.d
  1. #!/usr/bin/env dub
  2. /+dub.sdl:
  3. dependency "vibe-d" version="~>0.9"
  4. versions "VibeNoSSL"
  5. +/
  6.  
  7. import vibe.d;
  8.  
  9. /*
  10. Provide a special API File Handler as Vibe.d's builtin serveStaticFiles
  11. doesn't deal well with query params.
  12. This will blindly check if the requestURI payload exists on the filesystem and if so, return the file.
  13.  
  14. It replaces `?` with `__` for Windows compatibility.
  15.  
  16. Params:
  17. skip = initial part of the requestURI to skip over
  18. folder = the base directory from which to serve API requests from
  19. */
  20. auto apiFileHandler(string skip, string folder) {
  21. import std.functional : toDelegate;
  22. void handler(HTTPServerRequest req, HTTPServerResponse res) {
  23. import std.algorithm : skipOver;
  24. import std.path : buildPath;
  25. import std.file : exists;
  26. // ? can't be part of path names on Windows
  27. auto requestURI = req.requestURI.replace("?", "__");
  28. requestURI.skipOver(skip);
  29. const reqFile = buildPath(folder, requestURI);
  30. if (reqFile.exists) {
  31. return req.sendFile(res, PosixPath(reqFile));
  32. }
  33. }
  34. return toDelegate(&handler);
  35. }
  36.  
  37. void main(string[] args)
  38. {
  39. import std.conv;
  40. immutable folder = readRequiredOption!string("folder", "Folder to service files from.");
  41. immutable port = readRequiredOption!ushort("port", "Port to use");
  42. auto router = new URLRouter;
  43. router.get("stop", (HTTPServerRequest req, HTTPServerResponse res){
  44. res.writeVoidBody;
  45. exitEventLoop();
  46. });
  47. router.get("/packages/gitcompatibledubpackage/1.0.2.zip", (req, res) {
  48. res.writeBody("", HTTPStatus.badGateway);
  49. });
  50. router.get("*", folder.serveStaticFiles);
  51. router.get("/fallback/*", folder.serveStaticFiles(new HTTPFileServerSettings("/fallback")));
  52. router.get("/api/*", apiFileHandler("/", folder));
  53. router.get("/fallback/api/*", apiFileHandler("/fallback/", folder));
  54. listenHTTP(text(":", port), router);
  55. runApplication();
  56. }