Command Palette

Search for a command to run...

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

actix-web

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

Actix Web is a high-performance async web framework for Rust. It provides type-safe extractors, routing, middleware and a built-in test harness for building…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub14 установок в других каталогах

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

Actix Web

Overview

Actix Web (current release 4.18, MSRV 1.89) is a Rust web framework built on async/await, with extractors for type-safe request parsing and a ResponseError trait for error-to-response mapping. The examples below build a small articles API on PostgreSQL via sqlx. They were checked against the actix-web 4.18 sources and docs, not compiled here, so run cargo check after pasting.

Instructions

Installation

$ cargo new articles-api && cd articles-api
$ cargo add actix-web@4 [email protected] serde_json@1
$ cargo add serde@1 --features derive
$ cargo add [email protected] --features serde
$ cargo add [email protected] --features runtime-tokio,postgres,macros,chrono

actix-rt and a direct tokio dependency are not needed: #[actix_web::main] and #[actix_web::test] come with actix-web. sqlx 0.9 also exists (MSRV 1.94; query*() accept only &'static str or AssertSqlSafe(..)), which these literal queries satisfy.

CREATE TABLE articles (
  id SERIAL PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL,
  published BOOLEAN NOT NULL DEFAULT true, created_at TIMESTAMP NOT NULL DEFAULT now()
);

Main and Server Setup

// src/main.rs — application entry point
use actix_web::{middleware::Logger, web, App, HttpServer};
use sqlx::postgres::PgPoolOptions;

mod errors; mod middleware; mod models; mod routes;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // Logger writes through the `log` crate; set RUST_LOG=info to see requests
    env_logger::init();

    let database_url = std::env::var("DATABASE_URL")
        .unwrap_or_else(|_| "postgres://articles:[email protected]/articles".to_string());

    let pool = PgPoolOptions::new().max_connections(10)
        .connect(&database_url).await.expect("Failed to create pool");

    HttpServer::new(move || {
        App::new()
            .wrap(Logger::default())
            .app_data(web::Data::new(pool.clone())) // PgPool is already an Arc inside
            .app_data(web::JsonConfig::default().limit(64 * 1024)) // default is 2 MiB
            .configure(routes::configure)
    })
    // 127.0.0.1 for local work; use 0.0.0.0 only inside a container behind a proxy
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

Each mod also needs its file: src/models/mod.rs with pub mod article;, src/middleware/mod.rs with pub mod auth;, and src/routes/health.rs with a pub async fn check, like the one in Testing below.

Route Configuration

// src/routes/mod.rs
use actix_web::{middleware::from_fn, web};

mod articles; mod health;

pub fn configure(cfg: &mut web::ServiceConfig) {
    cfg.service(
        web::scope("/api")
            .route("/health", web::get().to(health::check))
            .service(
                web::scope("/articles")
                    .route("", web::get().to(articles::list))
                    .route("/{id}", web::get().to(articles::get)),
            )
            // writes live under a separate scope so only they need the API key
            .service(
                web::scope("/admin/articles")
                    .wrap(from_fn(crate::middleware::auth::require_api_key))
                    .route("", web::post().to(articles::create)),
            ),
    );
}

Models

// src/models/article.rs — data models with serde
use serde::{Deserialize, Serialize};
use sqlx::FromRow;

#[derive(Debug, Serialize, FromRow)]
pub struct Article {
    pub id: i32, pub title: String, pub body: String, pub published: bool,
    pub created_at: chrono::NaiveDateTime, // needs chrono's "serde" feature
}

#[derive(Debug, Deserialize)]
pub struct CreateArticle { pub title: String, pub body: String }

#[derive(Debug, Deserialize)]
pub struct ListParams { pub page: Option<u32>, pub limit: Option<u32> }

Handlers with Extractors

// src/routes/articles.rs — request handlers
use actix_web::{web, HttpResponse};
use sqlx::PgPool;
use crate::models::article::{Article, CreateArticle, ListParams};
use crate::errors::AppError;

pub async fn list(
    pool: web::Data<PgPool>,
    query: web::Query<ListParams>,
) -> Result<HttpResponse, AppError> {
    let limit = query.limit.unwrap_or(20).min(100) as i64;
    let offset = (query.page.unwrap_or(1).saturating_sub(1) as i64) * limit; // page 0 must not underflow

    let articles = sqlx::query_as::<_, Article>(
        "SELECT * FROM articles WHERE published ORDER BY created_at DESC LIMIT $1 OFFSET $2",
    )
    .bind(limit).bind(offset)
    .fetch_all(pool.get_ref())
    .await?;

    Ok(HttpResponse::Ok().json(articles))
}

pub async fn create(
    pool: web::Data<PgPool>,
    body: web::Json<CreateArticle>,
) -> Result<HttpResponse, AppError> {
    let article = sqlx::query_as::<_, Article>(
        "INSERT INTO articles (title, body) VALUES ($1, $2) RETURNING *"
    )
    .bind(&body.title).bind(&body.body)
    .fetch_one(pool.get_ref())
    .await?;

    Ok(HttpResponse::Created().json(artic
Полный SKILL.md на GitHub

Установить actix-web в Claude Code и Claude Desktop

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

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

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

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

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

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

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

_scores.json

FAQ

Что делает скилл actix-web?

Actix Web is a high-performance async web framework for Rust. It provides type-safe extractors, routing, middleware and a built-in test harness for building fast, memory-safe HTTP APIs. Use when a user asks to build a Rust REST API, add an Actix handler or middleware, handle errors with ResponseError, share a database pool, or test an Actix service.

Как установить скилл actix-web?

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

Скилл actix-web запускает скрипты?

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

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

Сравнить actix-web с