LoginSignup
1

More than 5 years have passed since last update.

CeylonでHTTPサーバを作ってみる

Last updated at Posted at 2013-12-06

前回 はJavaのクラスを使って
HTTPサーバを作りましたが
今回はCeylonのモジュールのみでHTTPサーバを作ってみます。

モジュール設定に追加

まずはモジュール設定ににceylon.netを追加します。


module com.hello.ceylonserver "1.0.0" {
    import ceylon.net "1.0.1";
}

今回は一行だけですね。

ではCeylonコード

import ceylon.io {
    SocketAddress
}
import ceylon.net.http.server {
    Endpoint,
    Response,
    Request,
    newServer,
    startsWith
}

void runServer() {

    value server = newServer {

        Endpoint {

            path = startsWith("/hello");

            service(Request request, Response response) =>
                    response.writeString("hello world");
        }
    };

    server.start(SocketAddress("localhost", 8080));
}

こんな感じでしたー。

シンプルですね。

特に説明無くても分かっちゃいますね。

一番べたにいろんなパスを追加するにはEndpointを複数渡してあげればOKです。

import ceylon.io {
    SocketAddress
}
import ceylon.net.http.server {
    Endpoint,
    Response,
    Request,
    newServer,
    startsWith
}

void runServer() {

    value server = newServer {

        Endpoint {

            path = startsWith("/hello");

            service(Request request, Response response) =>
                    response.writeString("hello world");
        }
        ,
        Endpoint {
            path = startsWith("/ceylon");

            service(Request request, Response response) =>
                    response.writeString("hello ceylon");

        }
    };

    server.start(SocketAddress("localhost", 8080));
}


こんな感じにすると

http://localhost:8080/ceylon

にアクセスすると

hello ceylon

が表示されます。

もちろんEndpointを追加するのではなく
受け取った後に処理を分岐するようにしても良いかと思います。

自由ですね。

シンプルにHTTPサーバも作れちゃいます。
どうでしょ?

Ceylon面白いかもしれないです。

今回はまだ説明していない呼び出し方法を使ってしまいました。
まだ良く分からないかもって人は
その辺は 次回 に書いているので見てみてね。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1