SSS(G) Dartハッカソン

アナウンス

Dart言語を使って何か作ってみよう、というイベントです。

詳細

  • 用意するもの:
    • 各自
      • ノートPC
      • Dart Editor

参加者

天野、小山、長沼、松山、宮澤

メモ

  • JSON Client/Server by Dart v0.3 ... ファイル, DBを読んで返却するようにしました。mongo-db と mongo-dart が必要です。
     ----- mongowebserver.dart
     #library('mongowebserver');
     #import('dart:io');
     #import('httpserver.dart');
     #import('mongo.dart');
     
     void main() {
       File script = new File(new Options().script);
       script.directory((Directory d) {
         new SimpleHttpServer(d.path).run();
       });
     }
     
     ----- mongo.dart
     #library('mongowebserver');
     #import ('mongo-dart/lib/mongo.dart');
     
     class MongoDb {
       int currentId = 0;
     
       MongoDb() {
         var db = new Db('sssg');
         db.open().then((e) {
           var col = db.collection('echo-server');
           col.remove();
           db.close();
         });
       }
       void dataInsert(String m) {
         var db = new Db('sssg');
         db.open().then((e) {
           var col = db.collection('echo-server');
           col.insert({'id': "${currentId++}", 'message': '${m}' });
           db.close();
         });
       }  
       void dataSelect(Function f) {
         var db = new Db('sssg');
         db.open().then((e) {
           var col = db.collection('echo-server');
           col.find({}).toList().then((List<Map> elems) {
             List<Map> entries = new List<Map>();
             for (final Map elem in elems) {
               entries.add(elem);
             }
             f(entries);
             db.close();
           });      
         });
       }
     }
     
     ----- httpserver.dart
     #library('mongowebserver');
     #import('dart:io');
     #import('dart:json');
     #import('mongo.dart');
     
     class SimpleHttpServer {
       final HOST = '127.0.0.1';
       final PORT = 8080;
       final String MSG_404 = '404 not found.';
       final LOG_REQUESTS = true;
       String _basePath;
       HttpServer _server;
       MongoDb _mongodb;
       
       SimpleHttpServer(this._basePath) {
         _server = new HttpServer();
         _server.defaultRequestHandler = root_handler;
         _mongodb = new MongoDb();
         _mongodb.dataInsert("msg00");
         _mongodb.dataInsert("msg01");
       }
       void run() {
         _server.listen(HOST, PORT);
         print('SimpleHttpServer start ${HOST}:${PORT}.');
       }
     
       void root_handler(HttpRequest req, HttpResponse res) {
         if (LOG_REQUESTS) {
           print('Request root_handler: ${req.method} ${req.uri} ${req.path}');
         }
         if (req.method.toString() == 'GET') {
           doGet(req, res);
         } else if (req.method.toString() == 'POST') {
           doPost(req, res);
         } else {
           doGet(req, res);
         }
         //print(res.headers);
       }
       void doGet(HttpRequest req, HttpResponse res) {
         var path = req.path == '/' ? '/index.html' : req.path;
         if (path == '/dart/api/data.json') {
           _mongodb.dataSelect((List<Map> entries){
             String contentType = 'application/json';
             List<String> entriesList = new List<String>();
             for (final Map e in entries) {
               entriesList.add('{"id":"${e["id"]}", "message":"${e["message"]}"}');
             }
             String s = entriesList.toString();
             print("doGet s :${s}");
             res.headers.set(HttpHeaders.CONTENT_TYPE, contentType);
             res.outputStream.writeString(s);
             res.outputStream.close();
           });
         } else {
           var file = new File('${_basePath}${path}');
           file.exists((found) { 
             if (found) {
               file.openInputStream().pipe(res.outputStream);
             } else {
               res.statusCode = HttpStatus.NOT_FOUND;
               String s = MSG_404;
               res.outputStream.writeString(s);
               res.outputStream.close();
             }
           });
         }
       }
       void doPost(HttpRequest req, HttpResponse res) {
         do404(req, res);
       }
       void do404(HttpRequest req, HttpResponse res) {
         String contentType = 'text/html; charset=UTF-8';
         String s = MSG_404;
         res.headers.set(HttpHeaders.CONTENT_TYPE, contentType);
         res.outputStream.writeString(s);
         res.statusCode = HttpStatus.NOT_FOUND;
         res.outputStream.close();
       }
     }
     
     ----- client.dart
     #import("dart:html");
     #import('dart:json');
     
     class client {
       String endpoint;
       
       client(endpoint) {
         this.endpoint = endpoint;
       }
     
       void render(List data) {
         StringBuffer sb = new StringBuffer();
         sb.add('<ul>');
         for (final Map m in data) { 
           sb.add('<li>${m['id']}:${m['message']}</li>');
         }
         sb.add('</ul>');
         write(sb.toString());
       }
     
       void run() {
         document.query("#status").innerHTML = "dart is running";
         reload();
       }
     
       void write(String message) {
         document.query("#datalist").innerHTML = message;
       }
     
       void reload() {
         var request = new XMLHttpRequest.getTEMPNAME(this.endpoint, (XMLHttpRequest req) {
           render(JSON.parse(req.responseText));
         });
       }
     }
     
     void main() {
       new client('http://127.0.0.1:8080/dart/api/data.json').run();
     }
     
     ----- client.html
     <!DOCTYPE html>
     
     <html>
       <head>
         <title>client</title>
       </head>
       <body>
         <h1>client</h1>
         <h2 id="status">dart is not running</h2>
         <div id="datalist">no data</div>
         <script type="application/dart" src="client.dart"></script>
         <script src="http://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
         
         <form id="entry-form">
           <input name="message" />
         </form>
       </body>
     </html>
  • JSON Client/Server by Dart v0.2 ... ファイルを読んで返却するようにしました。
     #library("http_server");
     #import("dart:io");
     #import("dart:json");
     
     class SimpleHttpServer {
       final HOST = "127.0.0.1";
       final PORT = 8080;
       final String MSG_404 = "404 not found.";
       final LOG_REQUESTS = true;
       String _basePath;
       HttpServer _server;
       
       SimpleHttpServer(this._basePath) {
         _server = new HttpServer();
         _server.defaultRequestHandler = root_handler;
       }
       void run() {
         _server.listen(HOST, PORT);
         print("SimpleHttpServer start ${HOST}:${PORT}.");
       }
     
       void root_handler(HttpRequest req, HttpResponse res) {
         if (LOG_REQUESTS) {
           print("Request root_handler: ${req.method} ${req.uri} ${req.path}");
         }
         if (req.method.toString() == 'GET') {
           doGet(req, res);
         } else if (req.method.toString() == 'POST') {
           doPost(req, res);
         } else {
           doGet(req, res);
         }
         //print(res.headers);
       }
       void doGet(HttpRequest req, HttpResponse res) {
         var path = req.path == '/' ? '/index.html' : req.path;
         var file = new File('${_basePath}${path}');
         file.exists((found) { 
           if (found) {
             file.openInputStream().pipe(res.outputStream);
           } else {
             res.statusCode = HttpStatus.NOT_FOUND;
             String s = MSG_404;
             res.outputStream.writeString(s);
             res.outputStream.close();
           }
         });
       }
       void doPost(HttpRequest req, HttpResponse res) {
         do404(req, res);
       }
       void do404(HttpRequest req, HttpResponse res) {
         String contentType = "text/html; charset=UTF-8";
         String s = MSG_404;
         res.headers.set(HttpHeaders.CONTENT_TYPE, contentType);
         res.outputStream.writeString(s);
         res.statusCode = HttpStatus.NOT_FOUND;
         res.outputStream.close();
       }
     }
     
     void main() {
       File script = new File(new Options().script);
       script.directory((Directory d) {
         new SimpleHttpServer(d.path).run();
       });
     }
  • JSON Client/Server by Dart v0.1 ... テキストデータでHTMLなどを用意して返します
     #library("hello_server");
     #import("dart:io");
     #import("dart:json");
     
     final HOST = "127.0.0.1";
     final PORT = 8080;
     final LOG_REQUESTS = true;
      
         String h = @'''
     <!DOCTYPE html>
     
     <html>
       <head>
         <title>client</title>
       </head>
       <body>
         <h1>client</h1>
         <h2 id="status">dart is not running</h2>
         <div id="datalist">no data</div>
         <script type="application/dart" src="client.dart"></script>
         <script src="http://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
         
         <form id="entry-form">
           <input name="message" />
         </form>
       </body>
     </html>
     ''';
         String d = @'''
     [
       {"id":"1", "message":"sample1"},
       {"id":"2", "message":"sample2"}
     ]
     ''';
         String s = @'''
     #import("dart:html");
     #import('dart:json');
     
     class client {
       String endpoint;
       
       client(endpoint) {
         this.endpoint = endpoint;
       }
     
       void render(List data) {
         StringBuffer sb = new StringBuffer();
         sb.add('<ul>');
         for (final Map m in data) { 
           sb.add('<li>${m['id']}:${m['message']}</li>');
         }
         sb.add('</ul>');
         write(sb.toString());
       }
     
       void run() {
         document.query("#status").innerHTML = "dart is running";
         reload();
       }
     
       void write(String message) {
         document.query("#datalist").innerHTML = message;
       }
     
       void reload() {
         var request = new XMLHttpRequest.getTEMPNAME(this.endpoint, (XMLHttpRequest req) {
           render(JSON.parse(req.responseText));
         });
       }
     }
     
     void main() {
       new client('http://127.0.0.1:8080/dart/api/data.json').run();
     }
     ''';
         String r = @'''
           <html>
           <body>
             <p>Hello</p>
           </body>
         </html>
     ''';
     
     void root_handler(HttpRequest req, HttpResponse res) {
       if (LOG_REQUESTS) {
         print("Request root_handler: ${req.method} ${req.uri} ${req.path}");
       }
       if (req.method.toString() == 'GET') {
         print("req.method: ${req.method}");
         if (req.path.toString() == '/client.html') {
           res.headers.set(HttpHeaders.CONTENT_TYPE, "text/html; charset=UTF-8");
           res.outputStream.writeString(h);
         } else if (req.path.toString() == '/dart/api/data.json') {
           res.headers.set(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
           print("data:${d}");
           res.outputStream.writeString(d);
         } else if (req.path.toString() == '/client.dart') {
           res.headers.set(HttpHeaders.CONTENT_TYPE, "application/dart");
           res.outputStream.writeString(s);
         } else {
           res.headers.set(HttpHeaders.CONTENT_TYPE, "text/html; charset=UTF-8");
           res.outputStream.writeString(r);
         }
       } else {
       }
       print(res.headers);
       res.outputStream.close();    
     }
     
     void main() {
       HttpServer server = new HttpServer();
       server.defaultRequestHandler = root_handler;
       server.listen(HOST, PORT);
       print("Hello on http://${HOST}:${PORT}.");
     }