コンテンツにスキップ

Hello World

最初のWippyアプリケーション - JSONを返すシンプルなHTTP API。

1つのエンドポイントを持つ最小限のWeb API:

GET /hello → {"message": "hello world"}
hello-world/
├── wippy.lock # 生成されたロックファイル
└── src/
├── _index.yaml # エントリ定義
└── hello.lua # ハンドラコード

ステップ1: プロジェクトディレクトリの作成

Section titled “ステップ1: プロジェクトディレクトリの作成”
Terminal window
mkdir hello-world && cd hello-world
mkdir src

src/_index.yamlを作成:

version: "1.0"
namespace: app
entries:
# HTTPサーバー
- name: gateway
kind: http.service
addr: ":8080"
lifecycle:
auto_start: true
# ルーター
- name: api
kind: http.router
meta:
server: app:gateway
prefix: /
# ハンドラ関数
- name: hello
kind: function.lua
source: file://hello.lua
method: handler
modules:
- http
# エンドポイント
- name: hello.endpoint
kind: http.endpoint
meta:
router: app:api
method: GET
func: app:hello
path: /hello

4つのエントリが連携して動作:

  1. gateway - ポート8080でリッスンするHTTPサーバー
  2. api - meta.server経由でgatewayに接続されたルーター
  3. hello - リクエストを処理するLua関数
  4. hello.endpoint - GET /helloを関数にルーティング

src/hello.luaを作成:

local http = require("http")
local function handler()
local res = http.response()
res:set_content_type(http.CONTENT.JSON)
res:set_status(http.STATUS.OK)
res:write_json({message = "hello world"})
end
return {
handler = handler
}

httpモジュールはリクエスト/レスポンスオブジェクトへのアクセスを提供します。関数はエクスポートされたhandlerメソッドを持つテーブルを返します。

Terminal window
# ソースからロックファイルを生成
wippy init
# ランタイムを起動(-c でカラフルなコンソール出力)
wippy run -c

次のような出力が表示されます:

╦ ╦╦╔═╗╔═╗╦ ╦ Adaptive Application Runtime
║║║║╠═╝╠═╝╚╦╝ v0.1.20
╚╩╝╩╩ ╩ ╩ by Spiral Scout
0.00s INFO run runtime ready
0.11s INFO core service app:gateway is running {"details": "service listening on :8080"}
Terminal window
curl http://localhost:8080/hello

レスポンス:

{"message":"hello world"}
  1. gatewayがポート8080でTCP接続を受け入れる
  2. apiルーターがパスプレフィックス/に一致
  3. hello.endpointGET /helloに一致
  4. hello関数が実行されJSONレスポンスを書き込む
コマンド説明
wippy initsrc/からロックファイルを生成
wippy runロックファイルからランタイムを起動
wippy run -cカラフルなコンソール出力で起動
wippy run -v詳細なデバッグログで起動
wippy run -sサイレントモードで起動(コンソールログなし)