Dart hello server 2012/05/01版

Dart hello server | hiro345」は2012/04/25以降のDart SDKでは動作しません。修正版は次の通りです。

addRequestHandlerを使うようになったのと、HttpResponseへのヘッダ設定についてheaders.setを使うようになった点に注意です。

Dart hello server 2012/05/01版

#library("httpserver_v2");
#import("dart:io");
final HOST = "127.0.0.1";
final PORT = 8080;
final LOG_REQUESTS = true;

void main() {
  HttpServer server = new HttpServer();  
  server.addRequestHandler((HttpRequest req) => true, handler);
  server.listen(HOST, PORT);  
  print("httpserver_v2 on http://${HOST}:${PORT}."); 
}

void handler(HttpRequest req, HttpResponse res) {
  if (LOG_REQUESTS) {
    print("Request: ${req.method} ${req.uri}");
  }
  String html = '''
<html>
  <head>
    <title>httpserver_v2</title>
    <style>
      body { background-color: gray; }
      p { background-color: white; border-radius: 4px; border:solid 1px #555; }
    </style>
  </head>
  <body>
    <p> Hello: ${new Date.now()} </p>
  </body>
</html>
''';
  res.headers.set(HttpHeaders.CONTENT_TYPE, "text/html; charset=UTF-8");
  res.outputStream.writeString(html);
  res.outputStream.close();
}

軽めの用途であれば、これで十分ですね。

同じタグの記事: Dart
同じタグの記事: dartlang
同じカテゴリの記事: Program