app.d 11 KB

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