app.d 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import vibe.appmain;
  2. import vibe.d;
  3. import std.random;
  4. const worldSize = 10000;
  5. const fortunesSize = 100;
  6. const mongoUrl = "mongodb://127.0.0.1/";
  7. MongoClient mongo;
  8. MongoCollection worldCollection;
  9. MongoCollection fortunesCollection;
  10. shared static this()
  11. {
  12. mongo = connectMongoDB( mongoUrl );
  13. worldCollection = mongo.getCollection( "hello_world.World" );
  14. fortunesCollection = mongo.getCollection( "hello_world.Fortunes" );
  15. auto router = new URLRouter;
  16. router.get("/plaintext", &plaintext);
  17. router.get("/json", &json);
  18. router.get("/db", &db);
  19. router.get("/queries", &queries);
  20. router.get("/generate-world", &generateWorld);
  21. router.get("/generate-fortunes", &generateFortunes);
  22. router.get("/", staticTemplate!"index.dt");
  23. auto settings = new HTTPServerSettings;
  24. settings.port = 8080;
  25. listenHTTP(settings, router);
  26. }
  27. void json(HTTPServerRequest req, HTTPServerResponse res)
  28. {
  29. auto helloWorld = Json([
  30. "message" : *new Json( "Hello, World!" )
  31. ]);
  32. res.writeJsonBody( helloWorld );
  33. }
  34. void generateWorld(HTTPServerRequest req, HTTPServerResponse res)
  35. {
  36. try {
  37. worldCollection.drop();
  38. } catch( Exception error ) {}
  39. for( auto i = 0 ; i < worldSize ; ++i ) {
  40. worldCollection.insert([
  41. "_id": i + 1,
  42. "randomNumber": uniform( 0 , worldSize )
  43. ]);
  44. }
  45. res.writeBody( "Generated" );
  46. }
  47. void generateFortunes(HTTPServerRequest req, HTTPServerResponse res)
  48. {
  49. try {
  50. fortunesCollection.drop();
  51. } catch( Exception error ) {}
  52. for( uint i = 0 ; i < worldSize ; ++i ) {
  53. fortunesCollection.insert([
  54. "_id": new Bson( i + 1 ),
  55. "message": new Bson( to!string( uniform( 0 , fortunesSize ) ) )
  56. ]);
  57. }
  58. res.writeBody( "Generated" );
  59. }
  60. void db(HTTPServerRequest req, HTTPServerResponse res)
  61. {
  62. auto data = worldCollection.findOne([
  63. "_id": uniform( 1 , worldSize + 1 )
  64. ]);
  65. res.writeJsonBody( data );
  66. }
  67. void queries(HTTPServerRequest req, HTTPServerResponse res)
  68. {
  69. auto count = 1;
  70. try {
  71. count = to!uint( req.query["queries"] );
  72. if( !count ) {
  73. count = 1;
  74. } else if( count > 500 ) {
  75. count = 500;
  76. }
  77. } catch( Exception error ) { }
  78. auto data = new Bson[ count ];
  79. for( uint i = 0 ; i < count ; ++i ) {
  80. data[i] = worldCollection.findOne([
  81. "_id": uniform( 1 , worldSize + 1 )
  82. ]);
  83. }
  84. res.writeJsonBody( data );
  85. }
  86. void plaintext(HTTPServerRequest req, HTTPServerResponse res)
  87. {
  88. res.writeBody("Hello, World!");
  89. }