Open2

Rust API 作成 , Workers デプロイ

knaka Tech-Blogknaka Tech-Blog

概要

  • Rust API , CF Workers デプロイ

[ 公開 2025/06/20 ]


環境

  • rustc 1.87.0
  • cargo 1.87.0
  • ubuntu 22 (windows WSL)
  • node 20

関連

https://zenn.dev/tfutada/articles/f6be3049d5f7fe


  • 上記の、参考記事を参考に。ビルド、workers デプロイできました。

準備など

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  • ccのエラーの場合、 gccインストールしました。
  • Workers-rsの、ビルド時に、build/worker/ 下に。index.wasmが出力されたので。
  • WASM使用かもしれないです。
  • wasm-pack install たしか下記 (参考)
cargo install wasm-pack

その他、参考ページ


Rustビルド、workers起動


  • Rust build
cargo build
  • dev-start
npm i
npm run dev

  • workers-rs-2/src/lib.rs
use worker::*;

#[event(fetch)]
async fn main(req: Request, env: Env, ctx: Context) -> Result<Response> {
    let  a = req.headers().get("x-forwarded-for").unwrap();

    Response::ok("Hello, World-55!")
}
npm run deploy

ルーティング , workers-rs


関連

https://github.com/cloudflare/workers-rs/tree/main/examples/router


環境

  • rustc 1.87.0
  • cargo 1.87.0
  • ubuntu 22 (windows WSL)
  • node 20

書いたコード

https://gist.github.com/kuc-arc-f/d176d608fbebb64038bcde2e5b37803c


  • Cargo.toml
[package]
name = "workers-rs-2"
version = "0.1.0"
edition = "2021"

# https://github.com/rustwasm/wasm-pack/issues/1247
[package.metadata.wasm-pack.profile.release]
wasm-opt = false

[lib]
crate-type = ["cdylib"]

[dependencies]
worker = { version = "0.6.0", features = ["d1"] }
serde = { version = "1.0.188", features = ["derive"] }

[dev-dependencies]
tokio = { version = "1", features = ["full"] }

[profile.release]
lto = true
strip = true
codegen-units = 1

  • src/lib.rs
  • main内で、ルーティング定義、handler関数を設定
  • /foo : GET通信
  • /bar: POST通信
use serde::{Deserialize, Serialize};
use worker::*;

#[derive(Debug, Deserialize, Serialize)]
struct GenericResponse {
    status: u16,
    message: String,
}

#[event(fetch)]
async fn main(req: Request, env: Env, _ctx: Context) -> Result<Response> {
    Router::new()
        .get_async("/foo", handle_get)
        .post_async("/bar", handle_post)
        .delete_async("/baz", handle_delete)
        .run(req, env)
        .await
}

pub async fn handle_get(_: Request, _ctx: RouteContext<()>) -> worker::Result<Response> {
    Response::from_json(&GenericResponse {
        status: 200,
        message: "You reached a GET route!".to_string(),
    })
}

pub async fn handle_post(_: Request, _ctx: RouteContext<()>) -> worker::Result<Response> {
    Response::from_json(&GenericResponse {
        status: 200,
        message: "You reached a POST route!".to_string(),
    })
}

pub async fn handle_delete(_: Request, _ctx: RouteContext<()>) -> worker::Result<Response> {
    Response::from_json(&GenericResponse {
        status: 200,
        message: "You reached a DELETE route!".to_string(),
    })
}

knaka Tech-Blogknaka Tech-Blog

D1 Databsese + workers-rs

  • D1 + CRUD的な API作成の例になります

環境

  • rustc 1.87.0
  • cargo 1.87.0
  • ubuntu 22 (windows WSL)
  • node 20
  • D1

書いたコード

https://github.com/kuc-arc-f/workers-api-rs-1/tree/main/workers-rs-4


  • Table
CREATE TABLE todos (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  title TEXT NOT NULL,
  description TEXT,
  completed BOOLEAN DEFAULT 0,
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL
)

  • DB, Table 作成の記事 (参考)

https://zenn.dev/knaka0209/scraps/8288ab9df79627


  • dev-start
cargo build
  • node
npm i
npm run dev

  • wrangler.toml
  • d1: database_name , database_id 設定
name = "workers-rs-2"
main = "build/worker/shim.mjs"
compatibility_date = "2023-03-22"
nodejs_compat = true

[build]
command = "cargo install -q worker-build && worker-build --release"

[[d1_databases]]
binding = "DB"
database_name = "db123"
database_id = ""


  • CRUD的な API
  • Rustよくわからず。。 AIコーディング(claude code)
  • 生成エラー多め、修正プロンプト入力、再修正が続きました。
  • workers-rs-4/src/lib.rs
  • エンドポイント: list , create , delete , update

https://github.com/kuc-arc-f/workers-api-rs-1/blob/main/workers-rs-4/src/lib.rs