app.d 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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.stdio;
  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 std.file : read;
  24. import toml;
  25. TOMLDocument toml_s;
  26. /* test unproper arguments order */
  27. /* do not */
  28. /*
  29. alias test_key1 = int;
  30. alias test_key2 = int;
  31. string test_args_types_mismash(test_key1 x, test_key2 y){
  32. return ( to!string(x) ~ " + " ~ to!string(y) ~ " = " ~ to!string( x + y ) );
  33. }
  34. */
  35. /* do not */
  36. /*
  37. import std.typecons : Typedef;
  38. alias test_key5 = Typedef!int;
  39. alias test_key6 = Typedef!int;
  40. string test_args_types_mismash(test_key5 x, test_key6 y){
  41. return ( to!string(x) ~ " + " ~ to!string(y) ~ " = " ~ to!string( x + y ) );
  42. }
  43. */
  44. /* do like */
  45. import std.typecons : Typedef;
  46. alias test_key5 = Typedef!(int, int.init, "key5");
  47. alias test_key6 = Typedef!(int, int.init, "key6");
  48. string test_args_types_mismash(test_key5 x, test_key6 y){
  49. return ( to!string(x) ~ " + " ~ to!string(y) ~ " = " ~ to!string( x + y ) );
  50. }
  51. /* or - do like */
  52. struct test_key3 { int v; }
  53. struct test_key4 { int v; }
  54. string test_args_types_mismash2(test_key3 x, test_key4 y){
  55. return ( to!string(x.v) ~ " + " ~ to!string(y.v) ~ " = " ~ to!string( x.v + y.v ) );
  56. }
  57. void main(){
  58. auto settings = new HTTPServerSettings;
  59. settings.port = 8080;
  60. settings.bindAddresses = ["::1", "127.0.0.1"];
  61. toml_s = parseTOML(cast(string)read("settings.toml"));
  62. if( are_valid_config_values(toml_s) ){}else{ return; } // settings validation
  63. uint conn_num = cast(uint) toml_s[s_toml_db][s_toml_db_conn_num].integer();
  64. uint8 i = cast(uint8) conn_num;
  65. // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING
  66. // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS
  67. //client = new PostgresClient("host=localhost port=5432 dbname=mydb user=username password=pass connect_timeout=5", 100);
  68. writeln("i = ", i);
  69. while(i > 0){
  70. writeln("i = ", i);
  71. clients ~= new PostgresClient( "host=" ~ toml_s[s_toml_db][s_toml_db_host].str() ~
  72. " port=" ~ toml_s[s_toml_db][s_toml_db_port].str() ~
  73. " dbname=" ~ toml_s[s_toml_db][s_toml_db_name].str() ~
  74. " user=" ~ toml_s[s_toml_db][s_toml_db_user].str() ~
  75. " password=" ~ toml_s[s_toml_db][s_toml_db_pass].str() ~
  76. " connect_timeout=" ~ toml_s[s_toml_db][s_toml_db_conn_timeout].str(),
  77. conn_num );
  78. i--;
  79. }
  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. // settings keys
  116. string s_toml_db = "database";
  117. string s_toml_db_host = "host";
  118. string s_toml_db_port = "port";
  119. string s_toml_db_name = "dbname";
  120. string s_toml_db_user = "user";
  121. string s_toml_db_pass = "pass";
  122. string s_toml_db_conn_timeout = "connect_timeout";
  123. string s_toml_db_conn_num = "connections_number";
  124. bool are_valid_config_values(ref TOMLDocument toml_s){ // settings validation
  125. string invalid_settings = "invalid settings: ";
  126. string grumpy = " :(";
  127. string invalid_group = " group ";
  128. string invalid_key = " key" ~ grumpy;
  129. bool invalid_toml_group(string group){
  130. writeln(invalid_settings ~ group ~ invalid_group ~ grumpy); return false;
  131. }
  132. bool invalid_toml_value(string group, string key){
  133. writeln(invalid_settings ~ group ~ invalid_group ~ key ~ invalid_key ~ grumpy); return false;
  134. }
  135. if((s_toml_db in toml_s) != null){
  136. auto toml_db = toml_s[s_toml_db];
  137. if((s_toml_db_host in toml_db) != null){
  138. if(toml_db[s_toml_db_host].type == TOMLType.STRING){}else{ return invalid_toml_value(s_toml_db, s_toml_db_host); }
  139. }else{ return invalid_toml_value(s_toml_db, s_toml_db_host); }
  140. if((s_toml_db_port in toml_db) != null){
  141. if(toml_db[s_toml_db_port].type == TOMLType.STRING){}else{ return invalid_toml_value(s_toml_db, s_toml_db_port); }
  142. }else{ return invalid_toml_value(s_toml_db, s_toml_db_port); }
  143. if((s_toml_db_name in toml_db) != null){
  144. if(toml_db[s_toml_db_name].type == TOMLType.STRING){}else{ return invalid_toml_value(s_toml_db, s_toml_db_name); }
  145. }else{ return invalid_toml_value(s_toml_db, s_toml_db_name); }
  146. if((s_toml_db_user in toml_db) != null){
  147. if(toml_db[s_toml_db_user].type == TOMLType.STRING){}else{ return invalid_toml_value(s_toml_db, s_toml_db_user); }
  148. }else{ return invalid_toml_value(s_toml_db, s_toml_db_user); }
  149. if((s_toml_db_pass in toml_db) != null){
  150. if(toml_db[s_toml_db_pass].type == TOMLType.STRING){}else{ return invalid_toml_value(s_toml_db, s_toml_db_pass); }
  151. }else{ return invalid_toml_value(s_toml_db, s_toml_db_pass); }
  152. if((s_toml_db_conn_timeout in toml_db) != null){
  153. if(toml_db[s_toml_db_conn_timeout].type == TOMLType.STRING){}else{ return invalid_toml_value(s_toml_db, s_toml_db_conn_timeout); }
  154. }else{ return invalid_toml_value(s_toml_db, s_toml_db_conn_timeout); }
  155. if((s_toml_db_conn_num in toml_db) != null){
  156. if(toml_db[s_toml_db_conn_num].type == TOMLType.INTEGER){}else{ return invalid_toml_value(s_toml_db, s_toml_db_conn_num); }
  157. }else{ return invalid_toml_value(s_toml_db, s_toml_db_conn_num); }
  158. }else{ return invalid_toml_group(s_toml_db); }
  159. return true;
  160. }
  161. /*
  162. void test_pg_conn_driver(){ // https://github.com/denizzzka/vibe.d.db.postgresql/blob/master/example/example.d#L13
  163. client.pickConnection( (scope conn){
  164. immutable result = conn.exec(
  165. "SELECT 123 as first_num, 567 as second_num, 'abc'::text as third_text " ~
  166. "UNION ALL " ~
  167. "SELECT 890, 233, 'fgh'::text as third_text",
  168. ValueFormat.BINARY
  169. );
  170. assert(result[0]["second_num"].as!PGinteger == 567);
  171. assert(result[1]["third_text"].as!PGtext == "fgh");
  172. foreach (val; rangify(result[0])){
  173. writeln("Found entry: ", val.as!Bson.toJson);
  174. }
  175. } );
  176. }
  177. */
  178. string get_all_cities(){
  179. return "SELECT id, name, population FROM test ORDER BY id";
  180. }
  181. void test_pg_conn_driver_queries(){
  182. /*
  183. client.pickConnection( (scope conn){
  184. QueryParams params; // https://github.com/denizzzka/dpq2/blob/master/src/dpq2/args.d#L15
  185. params.preparedStatementName = "get_city_by_id";
  186. 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
  187. conn.prepareEx(params.preparedStatementName, "SELECT id, name, population FROM test WHERE id = $1"); // get_city_by_id
  188. auto result1 = conn.execPrepared(params);
  189. writeln("id: ", result1[0]["id"].as!PGinteger);
  190. writeln("name: ", result1[0]["name"].as!PGtext);
  191. writeln("population: ", result1[0]["population"].as!PGinteger);
  192. //conn.prepareEx("q1", "UPDATE test SET name = $1, population = $2 WHERE id = $3"); // update_city_by_id
  193. //immutable result1 = conn.execPrepared("", ValueFormat.BINARY);
  194. destroy(conn);
  195. } );
  196. */
  197. auto conn = clients[0].lockConnection(); // todo think is this correct to take index 0 here
  198. QueryParams params; // https://github.com/denizzzka/dpq2/blob/master/src/dpq2/args.d#L15
  199. params.preparedStatementName = "get_city_by_id";
  200. 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
  201. conn.prepareEx(params.preparedStatementName, "SELECT id, name, population FROM test WHERE id = $1"); // get_city_by_id
  202. auto result1 = conn.execPrepared(params);
  203. writeln("id: ", result1[0]["id"].as!PGinteger);
  204. writeln("name: ", result1[0]["name"].as!PGtext);
  205. writeln("population: ", result1[0]["population"].as!PGinteger);
  206. //conn.prepareEx("q1", "UPDATE test SET name = $1, population = $2 WHERE id = $3"); // update_city_by_id
  207. //immutable result1 = conn.execPrepared("", ValueFormat.BINARY);
  208. destroy(conn);
  209. }
  210. /*
  211. "SELECT id, name, population FROM test ORDER BY id"
  212. "UPDATE test SET name = $1, population = $2 WHERE id = $3", [City_Name, City_Pop, City_Id]
  213. "INSERT INTO test (name, population) VALUES ($1, $2)", [City_Name, City_Pop]
  214. "INSERT INTO test (name, population) VALUES ($1, $2) RETURNING id", [City_Name, City_Pop]
  215. "DELETE FROM test WHERE id = $1", [City_Id]
  216. */
  217. void test(HTTPServerRequest req, HTTPServerResponse res){
  218. auto cache = memcachedConnect("127.0.0.1:11211");
  219. /* test unproper arguments order */
  220. /* do not */
  221. /*
  222. test_key1 x = 5;
  223. test_key2 y = 2;
  224. //string r1 = test_args_types_mismash(x, y); // proper arguments order
  225. 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..
  226. writeln("r1 = ", r1);
  227. */
  228. /* do not */
  229. /*
  230. test_key5 x = 5;
  231. test_key6 y = 2;
  232. //string r3 = test_args_types_mismash(x, y); // proper arguments order
  233. 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..
  234. writeln("r3 = ", r3);
  235. */
  236. /* do like */
  237. test_key5 x = 5;
  238. test_key6 y = 2;
  239. string r3 = test_args_types_mismash(x, y); // proper arguments order
  240. //string r3 = test_args_types_mismash(y, x); // unproper - this not compiles
  241. writeln("r3 = ", r3);
  242. /* or - do like */
  243. test_key3 x2 = test_key3(5);
  244. test_key4 y2 = test_key4(2);
  245. string r2 = test_args_types_mismash2(x2, y2); // proper arguments order
  246. //string r2 = test_args_types_mismash2(y2, x2); // unproper - this not compiles
  247. writeln("r2 = ", r2);
  248. Language Lang = Language.uk;
  249. writeln("tr 1 = ", Tr(Lang, TKey.hello));
  250. writeln("tr 2 = ", Tr(Lang, TKey.welcome, ["username"], 0) );
  251. writeln("tr 3 = ", Tr(Lang, TKey.apples, [], 1) );
  252. writeln("tr 3 = ", Tr(Lang, TKey.apples, [], 2) ) ;
  253. writeln("tr 3 = ", Tr(Lang, TKey.apples, [], 5) );
  254. writeln("tr 4 = ", Tr(Lang, TKey.apples_n_oranges, ["6", "7"], 0) );
  255. writeln("get test1 = ", cache.get!string("test1"));
  256. string v1 = "value1 = 🔥🦀";
  257. if(cache.store("test1", v1) == RETURN_STATE.SUCCESS ){
  258. writeln("stored successfully");
  259. writeln("get stored: ", cache.get!string("test1") );
  260. }else{
  261. writeln("not stored");
  262. }
  263. string result = cache.get!string("test1");
  264. writeln("get test1 = ", result);
  265. writeln(cache.del("test1"));
  266. //test_pg_conn_driver();
  267. test_pg_conn_driver_queries();
  268. Mustache mustache2;
  269. auto context2 = new Mustache.Context;
  270. mustache2.path = "priv/folder2";
  271. mustache2.ext = "dtl";
  272. context2["param2"] = "blah blah blah ";
  273. Mustache mustache;
  274. auto context = new Mustache.Context;
  275. mustache.path = "priv";
  276. mustache.ext = "dtl";
  277. //context.useSection("boolean");
  278. //assert(mustache.renderString(" {{#boolean}}YES{{/boolean}}\n {{#boolean}}GOOD{{/boolean}}\n", context) == " YES\n GOOD\n");
  279. //{{escaped_html_tags}}
  280. //{{{not_escaped_html_tags}}}
  281. //{{#repo}}<b>{{name}}</b>{{/repo}}
  282. //{{^repo}}No repos :({{/repo}}
  283. // to
  284. //No repos :(
  285. context["lang"] = "en";
  286. context["number1"] = 42;
  287. context.useSection("maybe1");
  288. context["part1"] = mustache2.render("part1", context2);
  289. context["result1"] = "Hello, World!\n" ~ result;
  290. res.headers["Content-Type"] = "text/html; charset=utf-8";
  291. //res.writeBody("Hello, World!\n" ~ result);
  292. res.writeBody( mustache.render("main", context) );
  293. }