Web フレームワーク
NagiScript でシンプルな Web フレームワークを開発するチュートリアルです。
現行仕様(v0.2.0)
この例は現行仕様の構文(string 型、-> と明示 return、match、while)で書かれており、文法としては現行コンパイラー v0.2.0 で動作する形です。ルーティングは関数型フィールドではなく handler_id: i32 と if 分岐で実装します(関数型フィールドは現行では不安定)。
概要
このチュートリアルでは、NagiScript で基本的な Web フレームワーク(ルーティング部分)を作成します。
- リクエストとレスポンスの表現
- ハンドラ ID によるルーティング
- JSON レスポンス(enum による状態表現)
ロードマップ
実際の HTTP サーバ(std:net の listen / accept)や TCP ソケット操作は現行では未実装です。下記はルーティングロジックのみで、ネットワーク部分は将来仕様です。
実装(単一ファイル)
main.ngs
enum Status { Ok NotFound }
struct Request {
method: string
path: string
}
struct Response {
status: Status
body: string
}
fn home_handler() -> Response {
return Response { status: Status.Ok, body: "Welcome to NagiScript Web Framework!" }
}
fn hello_handler() -> Response {
return Response { status: Status.Ok, body: "Hello, World!" }
}
fn not_found() -> Response {
return Response { status: Status.NotFound, body: "Page not found" }
}
fn route(req: Request) -> Response {
if req.method == "GET" {
if req.path == "/" {
return home_handler()
}
if req.path == "/hello" {
return hello_handler()
}
}
return not_found()
}
fn main() {
// サンプルリクエストで動作確認
val r1 = Request { method: "GET", path: "/" }
val r2 = Request { method: "GET", path: "/hello" }
val r3 = Request { method: "GET", path: "/nope" }
val resp = match route(r1).status {
Ok => "200 OK",
_ => "404 Not Found",
}
println(resp)
println(route(r2).body)
println(route(r3).body)
}
ロードマップ
url のルーティング・JSON 直列化・HTTP プロトコル送受信は、std:net と標準ライブラリが未実装のため将来仕様です。上記は現行で動作確認できる構文例です。
実行例
bash
# ビルドと実行
nagiscript build main.ngs -o app
./app
# 出力例
200 OK
Hello, World!
Page not found
学べること
- ルーティング: パスに基づく分岐(
if) - enum: ステータスを
enum+matchで表現 - 明示 return: 各ハンドラで
-> Responseとreturn
