Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

rocket

БесплатноБез исполняемых скриптовНе проверен

Rocket is a Rust web framework for building type-safe HTTP APIs and web apps with attribute-macro routing, request guards, JSON and form handling, managed…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

Rocket — Type-Safe Rust Web Framework

Overview

Rocket (crate rocket, current release 0.5.2 of 23 October 2026, Rust 1.89 or newer) is an async Rust web framework built on tokio. Routes are plain functions annotated with #[get], #[post] and so on; path, query, body and header inputs are typed parameters, and a request that does not parse is rejected before your code runs. Cross-cutting concerns are request guards (types implementing FromRequest), managed state (.manage(...) and &State<T>), and fairings (lifecycle hooks). Rocket has no built-in CORS or database layer: use the separate rocket_db_pools crate (0.2) for databases, and a CORS crate or your own fairing. Rocket 0.5.2 is a security-fix release (updated rustls, tokio, hyper, time), so upgrade from earlier 0.5.x.

Instructions

  1. cargo add rocket --features json (add secrets for private cookies, tls for HTTPS). Put #[macro_use] extern crate rocket; at the top of main.rs.
  2. Entry point: #[launch] fn rocket() -> _ { rocket::build()... }. Mount routes with .mount("/api", routes![...]) and error handlers with .register("/", catchers![...]).
  3. Serde derives must point at Rocket's re-export: add #[serde(crate = "rocket::serde")] to structs, or add serde as your own dependency and drop the attribute.
  4. Return types map to responses: Option<T> gives 404 on None, Result<T, Status> gives the error status, (Status, Json<T>) sets the status, Json<T> serializes.
  5. Query parameters: #[get("/orders?<limit>")] with limit: Option<usize>; body: #[post("/orders", format = "json", data = "<input>")] with input: Json<NewOrder>. Add #[derive(FromForm)] for form and multi-value query structs.
  6. Authentication: implement FromRequest for a guard type and add it as a handler parameter. Return Outcome::Error((Status::Unauthorized, ...)) (0.5 name; Failure was the 0.5 release-candidate name) to reject.
  7. Shared state: .manage(value) and &State<T>; wrap mutable data in Mutex/RwLock or atomics.
  8. Config comes from Rocket.toml and ROCKET_* environment variables (ROCKET_PORT, ROCKET_ADDRESS, ROCKET_SECRET_KEY, ROCKET_PROFILE). The default address is 127.0.0.1:8000; in a container set ROCKET_ADDRESS=0.0.0.0. JSON bodies are limited to 1 MiB by default; raise with [default.limits] json = ....
  9. Test without a network using rocket::local::blocking::Client::tracked(rocket()) (or local::asynchronous::Client).
  10. Database: add rocket_db_pools with a driver feature (e.g. sqlx_sqlite, sqlx_postgres), #[derive(Database)] #[database("orders")] struct Db(sqlx::SqlitePool);, configure [default.databases.orders] url = "..." in Rocket.toml, .attach(Db::init()), and take Connection<Db> as a handler parameter.

Examples

In-memory orders API with an API-key guard and a response fairing

Request: "Build a small JSON API for orders where creating needs an API key."

# Cargo.toml
[dependencies]
rocket = { version = "0.5", features = ["json"] }
#[macro_use]
extern crate rocket;

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;

use rocket::fairing::{Fairing, Info, Kind};
use rocket::http::{Header, Status};
use rocket::request::{FromRequest, Outcome, Request};
use rocket::serde::json::{serde_json::json, Json, Value};
use rocket::serde::{Deserialize, Serialize};
use rocket::{Response, State};

#[derive(Serialize, Deserialize, Clone)]
#[serde(crate = "rocket::serde")]
struct Order { id: u64, customer: String, total_cents: u64 }

#[derive(Deserialize)]
#[serde(crate = "rocket::serde")]
struct NewOrder { customer: String, total_cents: u64 }

struct Store { next_id: AtomicU64, orders: Mutex<Vec<Order>> }

struct ApiKey;

#[rocket::async_trait]
impl<'r> FromRequest<'r> for ApiKey {
    type Error = &'static str;
    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
        match req.headers().get_one("x-api-key") {
            Some("secret-key-1") => Outcome::Success(ApiKey), // compare against a value from config in real code
            Some(_) => Outcome::Error((Status::Forbidden, "bad key")),
            None => Outcome::Error((Status::Unauthorized, "missing key")),
        }
    }
}

struct ServedBy;

#[rocket::async_trait]
impl Fairing for ServedBy {
    fn info(&self) -> Info { Info { name: "X-Served-By header", kind: Kind::Response } }
    async fn on_response<'r>(&self, _req: &'r Request<'_>, res: &mut Response<'r>) {
        res.set_header(Header::new("X-Served-By", "orders-api"));
    }
}

#[get("/orders?<limit>")]
fn list(store: &State<Store>, limit: Option<usize>) -> Json<Vec<Order>> {
    let orders = store.orders.lock().unwrap();
    Json(orders.iter().take(limit.unwrap_or(20)).cloned().collect())
}

#[get("/orders/<id>")]
fn get(store: &State<Store>, id: u64) -> Option<Json<Order>> {
    store.orders.lock().unwrap().iter().find(|o| o.id == id).cloned().map(Json)
}

#[post("/orders", format = "json", d
Полный SKILL.md на GitHub

Установить rocket в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл rocket?

Rocket is a Rust web framework for building type-safe HTTP APIs and web apps with attribute-macro routing, request guards, JSON and form handling, managed state and fairings. Use this skill when a user wants to write a Rust REST API with Rocket 0.5, add authentication through request guards, share a database pool, configure Rocket.toml, or unit-test routes with the local client.

Как установить скилл rocket?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл rocket запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить rocket с