app.d 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. alias uint8 = ubyte;
  2. //import vibe.vibe;
  3. // https://github.com/vibe-d/vibe.d/blob/master/source/vibe/vibe.d
  4. import vibe.core.core;
  5. import vibe.http.router;
  6. import vibe.http.server;
  7. import vibe.http.fileserver;
  8. import vibe.http.websockets;
  9. import vibe.core.log;
  10. import std.string;
  11. //import std.array;
  12. import memcached4d;
  13. import std.conv : to;
  14. import tr;
  15. import mustache;
  16. alias MustacheEngine!(string) Mustache;
  17. import vibe.db.postgresql;
  18. import vibe.data.bson;
  19. //import vibe.data.json;
  20. // https://github.com/vibe-d/vibe.d/blob/master/source/vibe/vibe.d
  21. PostgresClient[] clients;
  22. import settings_toml; // get settings from settings.toml, settings keys, settings validation etc
  23. /* test unproper arguments order */
  24. /* do not */
  25. /*
  26. alias test_key1 = int;
  27. alias test_key2 = int;
  28. string test_args_types_mismash(test_key1 x, test_key2 y){
  29. return ( to!string(x) ~ " + " ~ to!string(y) ~ " = " ~ to!string( x + y ) );
  30. }
  31. */
  32. /* do not */
  33. /*
  34. import std.typecons : Typedef;
  35. alias test_key5 = Typedef!int;
  36. alias test_key6 = Typedef!int;
  37. string test_args_types_mismash(test_key5 x, test_key6 y){
  38. return ( to!string(x) ~ " + " ~ to!string(y) ~ " = " ~ to!string( x + y ) );
  39. }
  40. */
  41. /* do like */
  42. import std.typecons : Typedef;
  43. alias test_key5 = Typedef!(int, int.init, "key5");
  44. alias test_key6 = Typedef!(int, int.init, "key6");
  45. string test_args_types_mismash(test_key5 x, test_key6 y){
  46. return ( to!string(x) ~ " + " ~ to!string(y) ~ " = " ~ to!string( x + y ) );
  47. }
  48. /* or - do like */
  49. struct test_key3 { int v; }
  50. struct test_key4 { int v; }
  51. string test_args_types_mismash2(test_key3 x, test_key4 y){
  52. return ( to!string(x.v) ~ " + " ~ to!string(y.v) ~ " = " ~ to!string( x.v + y.v ) );
  53. }
  54. void main(){
  55. read_settings_toml(); // read settings, settings validation
  56. uint conn_num = cast(uint) toml_s[s_toml_db][s_toml_db_conn_num].integer();
  57. uint8 i = cast(uint8) conn_num;
  58. // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING
  59. // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS
  60. //client = new PostgresClient("host=localhost port=5432 dbname=mydb user=username password=pass connect_timeout=5", 100);
  61. while(i > 0){
  62. //writeln("i = ", i);
  63. clients ~= new PostgresClient( "host=" ~ toml_s[s_toml_db][s_toml_db_host].str() ~
  64. " port=" ~ toml_s[s_toml_db][s_toml_db_port].str() ~
  65. " dbname=" ~ toml_s[s_toml_db][s_toml_db_name].str() ~
  66. " user=" ~ toml_s[s_toml_db][s_toml_db_user].str() ~
  67. " password=" ~ toml_s[s_toml_db][s_toml_db_pass].str() ~
  68. " connect_timeout=" ~ toml_s[s_toml_db][s_toml_db_conn_timeout].str(),
  69. conn_num,
  70. (scope Connection conn){
  71. conn.prepareEx("get_city_by_id", "SELECT id, name, population FROM test WHERE id = $1");
  72. } );
  73. i--;
  74. }
  75. auto settings = new HTTPServerSettings;
  76. //settings.port = 8080;
  77. //settings.bindAddresses = ["::1", "127.0.0.1"];
  78. settings.port = cast(ushort)toml_s[s_toml_http][s_toml_http_port].integer();
  79. settings.bindAddresses = [ toml_s[s_toml_http][s_toml_http_host].str().idup ];
  80. //auto fsettings = new HTTPFileServerSettings;
  81. //fsettings.serverPathPrefix = "/static";
  82. auto router = new URLRouter;
  83. //router.get("/", &index);
  84. ////router.get("static/*", serverStaticFiles("public/", fsettings) );
  85. //router.get("/", staticTemplate!"index.html");
  86. router.get("/", serveStaticFile("public/index.html") );
  87. router.get("/ws", handleWebSockets(&ws_handle) );
  88. router.get("/test", &test);
  89. router.get("*", serveStaticFiles("public/"));
  90. //auto listener = listenHTTP(settings, &hello);
  91. auto listener = listenHTTP(settings, router);
  92. scope (exit){
  93. listener.stopListening();
  94. }
  95. logInfo("Please open http://127.0.0.1:8080/ in your browser.");
  96. runApplication();
  97. }
  98. void ws_handle(scope WebSocket sock){
  99. // simple echo server + :)
  100. while(sock.connected){
  101. auto msg = sock.receiveText();
  102. sock.send(msg ~ " :)");
  103. }
  104. }
  105. /*
  106. void index(HTTPServerRequest req, HTTPServerResponse res){
  107. res.writeBody("Hello, World!");
  108. }
  109. */
  110. /*
  111. void hello(HTTPServerRequest req, HTTPServerResponse res){
  112. res.writeBody("Hello, World!");
  113. }
  114. */
  115. /*
  116. void test_pg_conn_driver(){ // https://github.com/denizzzka/vibe.d.db.postgresql/blob/master/example/example.d#L13
  117. client.pickConnection( (scope conn){
  118. immutable result = conn.exec(
  119. "SELECT 123 as first_num, 567 as second_num, 'abc'::text as third_text " ~
  120. "UNION ALL " ~
  121. "SELECT 890, 233, 'fgh'::text as third_text",
  122. ValueFormat.BINARY
  123. );
  124. assert(result[0]["second_num"].as!PGinteger == 567);
  125. assert(result[1]["third_text"].as!PGtext == "fgh");
  126. foreach (val; rangify(result[0])){
  127. writeln("Found entry: ", val.as!Bson.toJson);
  128. }
  129. } );
  130. }
  131. */
  132. string get_all_cities(){
  133. return "SELECT id, name, population FROM test ORDER BY id";
  134. }
  135. void test_pg_conn_driver_queries(){
  136. /*
  137. client.pickConnection( (scope conn){
  138. QueryParams params; // https://github.com/denizzzka/dpq2/blob/master/src/dpq2/args.d#L15
  139. params.preparedStatementName = "get_city_by_id";
  140. params.argsVariadic(3); // https://github.com/denizzzka/dpq2/blob/master/example/example.d#L42 // https://github.com/denizzzka/dpq2/blob/master/src/dpq2/query.d#L336 // https://github.com/denizzzka/vibe.d.db.postgresql/blob/master/source/vibe/db/postgresql/package.d#L423
  141. conn.prepareEx(params.preparedStatementName, "SELECT id, name, population FROM test WHERE id = $1"); // get_city_by_id
  142. auto result1 = conn.execPrepared(params);
  143. writeln("id: ", result1[0]["id"].as!PGinteger);
  144. writeln("name: ", result1[0]["name"].as!PGtext);
  145. writeln("population: ", result1[0]["population"].as!PGinteger);
  146. //conn.prepareEx("q1", "UPDATE test SET name = $1, population = $2 WHERE id = $3"); // update_city_by_id
  147. //immutable result1 = conn.execPrepared("", ValueFormat.BINARY);
  148. destroy(conn);
  149. } );
  150. */
  151. //auto conn = clients[0].lockConnection(); // todo think is this correct to take index 0 here
  152. clients[0].pickConnection( (scope conn){ // todo think is this correct to take index 0 here
  153. QueryParams params; // https://github.com/denizzzka/dpq2/blob/master/src/dpq2/args.d#L15
  154. params.preparedStatementName = "get_city_by_id";
  155. params.argsVariadic(3); // https://github.com/denizzzka/dpq2/blob/master/example/example.d#L42 // https://github.com/denizzzka/dpq2/blob/master/src/dpq2/query.d#L336 // https://github.com/denizzzka/vibe.d.db.postgresql/blob/master/source/vibe/db/postgresql/package.d#L423
  156. //conn.prepareEx(params.preparedStatementName, "SELECT id, name, population FROM test WHERE id = $1"); // get_city_by_id
  157. auto result1 = conn.execPrepared(params);
  158. writeln("id: ", result1[0]["id"].as!PGinteger);
  159. writeln("name: ", result1[0]["name"].as!PGtext);
  160. writeln("population: ", result1[0]["population"].as!PGinteger);
  161. //conn.prepareEx("q1", "UPDATE test SET name = $1, population = $2 WHERE id = $3"); // update_city_by_id
  162. //immutable result1 = conn.execPrepared("", ValueFormat.BINARY);
  163. destroy(conn);
  164. } );
  165. }
  166. /*
  167. "SELECT id, name, population FROM test ORDER BY id"
  168. "UPDATE test SET name = $1, population = $2 WHERE id = $3", [City_Name, City_Pop, City_Id]
  169. "INSERT INTO test (name, population) VALUES ($1, $2)", [City_Name, City_Pop]
  170. "INSERT INTO test (name, population) VALUES ($1, $2) RETURNING id", [City_Name, City_Pop]
  171. "DELETE FROM test WHERE id = $1", [City_Id]
  172. */
  173. void test(HTTPServerRequest req, HTTPServerResponse res){
  174. auto cache = memcachedConnect("127.0.0.1:11211");
  175. /* test unproper arguments order */
  176. /* do not */
  177. /*
  178. test_key1 x = 5;
  179. test_key2 y = 2;
  180. //string r1 = test_args_types_mismash(x, y); // proper arguments order
  181. string r1 = test_args_types_mismash(y, x); // unproper - this compiles but we got logic error bug in runtime.. :( use struct for compiler check this..
  182. writeln("r1 = ", r1);
  183. */
  184. /* do not */
  185. /*
  186. test_key5 x = 5;
  187. test_key6 y = 2;
  188. //string r3 = test_args_types_mismash(x, y); // proper arguments order
  189. string r3 = test_args_types_mismash(y, x); // unproper - this compiles but we got logic error bug in runtime.. :( use struct for compiler check this..
  190. writeln("r3 = ", r3);
  191. */
  192. /* do like */
  193. test_key5 x = 5;
  194. test_key6 y = 2;
  195. string r3 = test_args_types_mismash(x, y); // proper arguments order
  196. //string r3 = test_args_types_mismash(y, x); // unproper - this not compiles
  197. writeln("r3 = ", r3);
  198. /* or - do like */
  199. test_key3 x2 = test_key3(5);
  200. test_key4 y2 = test_key4(2);
  201. string r2 = test_args_types_mismash2(x2, y2); // proper arguments order
  202. //string r2 = test_args_types_mismash2(y2, x2); // unproper - this not compiles
  203. writeln("r2 = ", r2);
  204. Language Lang = Language.uk;
  205. writeln("tr 1 = ", Tr(Lang, TKey.hello));
  206. writeln("tr 2 = ", Tr(Lang, TKey.welcome, ["username"], 0) );
  207. writeln("tr 3 = ", Tr(Lang, TKey.apples, [], 1) );
  208. writeln("tr 3 = ", Tr(Lang, TKey.apples, [], 2) ) ;
  209. writeln("tr 3 = ", Tr(Lang, TKey.apples, [], 5) );
  210. writeln("tr 4 = ", Tr(Lang, TKey.apples_n_oranges, ["6", "7"], 0) );
  211. writeln("get test1 = ", cache.get!string("test1"));
  212. string v1 = "value1 = 🔥🦀";
  213. if(cache.store("test1", v1) == RETURN_STATE.SUCCESS ){
  214. writeln("stored successfully");
  215. writeln("get stored: ", cache.get!string("test1") );
  216. }else{
  217. writeln("not stored");
  218. }
  219. string result = cache.get!string("test1");
  220. writeln("get test1 = ", result);
  221. writeln(cache.del("test1"));
  222. //test_pg_conn_driver();
  223. test_pg_conn_driver_queries();
  224. Mustache mustache2;
  225. auto context2 = new Mustache.Context;
  226. mustache2.path = "priv/folder2";
  227. mustache2.ext = "dtl";
  228. context2["param2"] = "blah blah blah ";
  229. Mustache mustache;
  230. auto context = new Mustache.Context;
  231. mustache.path = "priv";
  232. mustache.ext = "dtl";
  233. //context.useSection("boolean");
  234. //assert(mustache.renderString(" {{#boolean}}YES{{/boolean}}\n {{#boolean}}GOOD{{/boolean}}\n", context) == " YES\n GOOD\n");
  235. //{{escaped_html_tags}}
  236. //{{{not_escaped_html_tags}}}
  237. //{{#repo}}<b>{{name}}</b>{{/repo}}
  238. //{{^repo}}No repos :({{/repo}}
  239. // to
  240. //No repos :(
  241. context["lang"] = "en";
  242. context["number1"] = 42;
  243. context.useSection("maybe1");
  244. context["part1"] = mustache2.render("part1", context2);
  245. context["result1"] = "Hello, World!\n" ~ result;
  246. res.headers["Content-Type"] = "text/html; charset=utf-8";
  247. //res.writeBody("Hello, World!\n" ~ result);
  248. res.writeBody( mustache.render("main", context) );
  249. }