ws_bert_login.d 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. alias uint8 = ubyte;
  2. import vibe.core.core;
  3. import vibe.http.router;
  4. import vibe.http.server;
  5. import vibe.http.fileserver;
  6. import vibe.http.websockets;
  7. import vibe.core.log;
  8. import std.stdio;
  9. import std.string;
  10. import std.array;
  11. import std.conv : to;
  12. import bert; // https://github.com/221V/dlang_erl_bert https://git.4dev.win/game1/dlang_erl_bert
  13. import mustache;
  14. alias MustacheEngine!(string) Mustache;
  15. void ws_bert_handle(scope WebSocket sock){
  16. // simple echo server + :)
  17. while(sock.connected){
  18. //auto msg = sock.receiveText();
  19. //sock.send(msg ~ " :)");
  20. auto msg = sock.receiveBinary();
  21. if(msg == "1"){
  22. sock.send("0"); // ws PING - PONG
  23. }else{
  24. try{
  25. auto decoder = new BertDecoder( cast(ubyte[])msg.dup );
  26. auto decoded = decoder.decode();
  27. msg_match(decoded, sock);
  28. }catch(Exception e){
  29. writeln("Exception 37: ", e.msg);
  30. }
  31. }
  32. }
  33. }
  34. void msg_match(BertValue decoded, WebSocket sock){
  35. writeln("Decoded: ", decoded.toString());
  36. if(decoded.type_ == BertType.Tuple){
  37. auto decoded1 = decoded.tupleValue;
  38. if(decoded1.length == 3){
  39. if(auto num1 = cast(uint8)decoded1[0].intValue){
  40. writeln("num1 = ", num1, " ", typeof(num1).stringof); // ws.send(enc(tuple( number(1), number(42), number(777) ))); // Decoded: {1, 42, 777} // num1 = 1 ubyte
  41. sock.send("{console.log(" ~ to!string(num1 + 42) ~ ")}"); // got 43 in browser console
  42. } // else do nothing
  43. } // else do nothing
  44. } // else do nothing
  45. }
  46. void login_test(HTTPServerRequest req, HTTPServerResponse res){
  47. Mustache mustache;
  48. auto context = new Mustache.Context;
  49. mustache.path = "priv";
  50. mustache.ext = "dtl";
  51. context["lang"] = "en";
  52. context["number1"] = 42;
  53. context.useSection("maybe1");
  54. context["part1"] = "<span>777</span>";
  55. context["result1"] = "Hello, World!\n";
  56. res.headers["Content-Type"] = "text/html; charset=utf-8";
  57. //res.writeBody("Hello, World!\n" ~ result);
  58. res.writeBody( mustache.render("login_test", context) );
  59. }