app.d 12 KB

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