תיעוד 219
שימוש ב-Workers KV ישירות מ-Rust
עודכן לאחרונה: 29 בינואר 2026
המדריך הזה ילמד אתכם איך לקרוא ולכתוב ל-KV ישירות מ-Rust באמצעות workers-rs.
#לפני שמתחילים
כל המדריכים מניחים שכבר השלמתם את מדריך תחילת העבודה, שמגדיר לכם חשבון Cloudflare Workers, C3, ו-Wrangler.
#דרישות מוקדמות
כדי להשלים את המדריך הזה, תצטרכו:
cargo install cargo-generate#1. יצירת פרויקט Worker ב-Rust
פתחו חלון טרמינל, והריצו את הפקודה הבאה כדי ליצור תבנית פרויקט Worker ב-Rust:
cargo generate cloudflare/workers-rsלאחר מכן בחרו את התבנית template/hello-world-http, תנו לפרויקט שם תיאורי ובחרו enter. פרויקט חדש אמור להיווצר בתיקייה שלכם. פתחו את הפרויקט בעורך והריצו npx wrangler dev כדי לקמפל ולהריץ את הפרויקט.
במדריך הזה תשתמשו ב-Workers KV מ-Rust כדי לבנות אפליקציה ששומרת ומאחזרת ערים לפי שם מדינה נתון.
#2. יצירת מרחב שמות KV
בטרמינל, השתמשו ב-Wrangler כדי ליצור מרחב שמות KV עבור cities. זה יוצר הגדרה שצריך להוסיף לפרויקט:
npx wrangler kv namespace create citiesכדי להוסיף את ההגדרה הזו לפרויקט, פתחו את קובץ Wrangler וצרו רשומה עבור kv_namespaces מעל פקודת ה-build:
{
"kv_namespaces": [
{
"binding": "cities",
"id": "e29b263ab50e42ce9b637fa8370175e8"
}
]
}[[kv_namespaces]]
binding = "cities"
id = "e29b263ab50e42ce9b637fa8370175e8"אחרי שההגדרה הזו מוגדרת, אפשר לגשת למרחב השמות KV עם ה-binding "cities" מ-Rust.
#3. כתיבת נתונים ל-KV
עבור האפליקציה הזו תיצרו שני נתיבים: נתיב POST לקבלה ושמירה של העיר ב-KV, ונתיב GET לאחזור העיר של מדינה נתונה. לדוגמה, בקשת POST אל /France עם גוף {"city": "Paris"} אמורה ליצור רשומה של Paris כעיר ב-France. בקשת GET אל /France אמורה לאחזר מ-KV ולהשיב עם Paris.
התקינו את Serde כתלות בפרויקט כדי לטפל ב-JSON באמצעות cargo add serde. לאחר מכן צרו נתב לאפליקציה ומבנה Country ב-src/lib.rs:
use serde::{Deserialize, Serialize};
use worker::*;
#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {
let router = Router::new();
#[derive(Serialize, Deserialize, Debug)]
struct Country {
city: String,
}
router
// TODO:
.post_async("/:country", |_, _| async move { Response::empty() })
// TODO:
.get_async("/:country", |_, _| async move { Response::empty() })
.run(req, env)
.await
}עבור מטפל ה-post, תאחזרו את שם המדינה מהנתיב ואת שם העיר מגוף הבקשה. לאחר מכן תשמרו זאת ב-KV כשהמדינה היא המפתח והעיר היא הערך. לבסוף, האפליקציה תשיב עם שם העיר:
.post_async("/:country", |mut req, ctx| async move {
let country = ctx.param("country").unwrap();
let city = match req.json::<Country>().await {
Ok(c) => c.city,
Err(_) => String::from(""),
};
if city.is_empty() {
return Response::error("Bad Request", 400);
};
return match ctx.kv("cities")?.put(country, &city)?.execute().await {
Ok(_) => Response::ok(city),
Err(_) => Response::error("Bad Request", 400),
};
})שמרו את הקובץ ובצעו בקשת POST כדי לבדוק את נקודת הקצה הזו:
curl --json '{"city": "Paris"}' http://localhost:8787/France#4. קריאת נתונים מ-KV
כדי לאחזר ערים שנשמרו ב-KV, כתבו נתיב GET ששולף את שם המדינה מהנתיב ומחפש ב-KV. צריך גם טיפול בשגיאות אם המדינה לא נמצאה:
.get_async("/:country", |_req, ctx| async move {
if let Some(country) = ctx.param("country") {
return match ctx.kv("cities")?.get(country).text().await? {
Some(city) => Response::ok(city),
None => Response::error("Country not found", 404),
};
}
Response::error("Bad Request", 400)
})שמרו ובצעו בקשת curl כדי לבדוק את נקודת הקצה:
curl http://localhost:8787/France#5. פריסת הפרויקט
קוד המקור של האפליקציה שהושלמה אמור לכלול את הדברים הבאים:
use serde::{Deserialize, Serialize};
use worker::*;
#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {
let router = Router::new();
#[derive(Serialize, Deserialize, Debug)]
struct Country {
city: String,
}
router
.post_async("/:country", |mut req, ctx| async move {
let country = ctx.param("country").unwrap();
let city = match req.json::<Country>().await {
Ok(c) => c.city,
Err(_) => String::from(""),
};
if city.is_empty() {
return Response::error("Bad Request", 400);
};
return match ctx.kv("cities")?.put(country, &city)?.execute().await {
Ok(_) => Response::ok(city),
Err(_) => Response::error("Bad Request", 400),
};
})
.get_async("/:country", |_req, ctx| async move {
if let Some(country) = ctx.param("country") {
return match ctx.kv("cities")?.get(country).text().await? {
Some(city) => Response::ok(city),
None => Response::error("Country not found", 404),
};
}
Response::error("Bad Request", 400)
})
.run(req, env)
.await
}כדי לפרוס את ה-Worker, הריצו את הפקודה הבאה:
npx wrangler deploy