Expand description
§afast
A high-performance Rust web framework that eliminates manual route definitions. Handlers are registered declaratively and the framework generates TypeScript and JavaScript client code automatically. Data transport uses a compact binary protocol over HTTP, WebSocket, or TCP.
§Quick Start
use afast::{AFast, handler, service, State, Data, Result};
use afast::{AFastDeserialize, AFastSerialize, Tag};
#[derive(Clone)]
struct AppState { db_url: String }
#[derive(AFastDeserialize, Tag)]
#[tag("Request body")]
struct HelloReq { name: String }
#[derive(AFastSerialize, Tag)]
#[tag("Response body")]
struct HelloResp { message: String }
#[handler(desc("Say hello"))]
async fn hello(
state: State<AppState>,
req: Data<HelloReq>,
) -> Result<HelloResp> {
Ok(HelloResp { message: format!("Hello, {}!", req.0.name) })
}
#[tokio::main]
async fn main() {
let svc = service!("api" => { h(hello) });
let app = AFast::new()
.state(AppState { db_url: "localhost".into() })
.service(svc)
.http("0.0.0.0:5000");
app.run().await.unwrap();
}§Core Concepts
§Handlers
A handler is an async function annotated with #[handler(desc("..."))].
The framework registers it automatically and dispatches binary protocol
requests to it. Handlers can extract shared state via State<T>,
request data via Data<T>, and auth context via Custom<T>.
use afast::{handler, Data, State, Result};
use afast::{AFastDeserialize, AFastSerialize, Tag};
#[derive(AFastDeserialize, Tag)]
#[tag("Login request")]
struct LoginReq { username: String, password: String }
#[derive(AFastSerialize, Tag)]
#[tag("Login response")]
struct LoginResp { token: String }
#[handler(desc("Login with username and password"))]
async fn login(
state: State<AppState>,
req: Data<LoginReq>,
) -> Result<LoginResp> {
// Validate credentials, generate token, etc.
Ok(LoginResp { token: "abc123".into() })
}Handler attributes:
desc("...")— Human-readable description (required)name("...")— Client-side method name overridecache(seconds)— Client-side cache durationrate_limit("id")— Rate-limit policy ID
§Services
A service groups handlers into a namespace. Each service generates a
separate client code file. Use the service! macro:
let svc = service!("api", "My API" => {
h(health),
group("user" => {
h(create_user),
h(list_users),
}),
});§Ordinary HTTP Routes
With the ordinary-http feature, you can define REST-style endpoints
using #[get], #[post], #[put], #[delete], #[patch] macros.
These use JSON request/response bodies instead of the binary protocol.
use afast::{get, post, Query, Param, Body, Json, HttpResult};
#[get(desc("List users"))]
async fn list_users(query: Query<ListQuery>) -> HttpResult<Json<UserList>> {
Ok(Json(UserList { total: 0, items: vec![] }))
}
#[post(desc("Create user"))]
async fn create_user(body: Body<CreateBody>) -> HttpResult<Json<User>> {
Ok(Json(User { id: 1, username: body.0.username }))
}§Error Handling
All handlers return Result<T>, which is Result<T, Error>.
Use Error::custom to create user-defined errors:
return Err(Error::custom(404, "user not found"));Custom error types can implement AFastError to be returned directly
from handlers.
§Features
| Feature | Description |
|---|---|
ws | WebSocket server via tokio-tungstenite |
http | HTTP server via hyper |
tcp | TCP server with length-prefix framing |
ts | TypeScript client code generation |
js | JavaScript client code generation |
kt | Kotlin client code generation |
rs | Rust client code generation |
code | HTTP endpoint for on-demand client code generation |
doc | Interactive API documentation page |
ordinary-http | REST-style HTTP endpoints with JSON request/response bodies |
ordinary-ws | Path-based WebSocket endpoints with text/JSON frames |
ordinary-sse | Server-Sent Events endpoints |
tls | HTTPS support via rustls with ALPN for HTTP/2 |
seq64 | Use i64 for WebSocket request IDs (default i32) |
len64 | Use u64 for WebSocket payload lengths (default u32) |
rate-limit | Request rate limiting with named policies and pluggable store |
hook | Request and connection lifecycle hooks |
marker | Conditional serialization with marker-based field skipping |
§Module Guide
| Module | Description |
|---|---|
error | Error types and error codes |
handler | Handler abstractions, metadata, and type tags |
service | Service container for grouping handlers |
state | Type-map for shared application state |
[hook] | Request/connection lifecycle hooks (feature hook) |
[rate_limit] | Rate limiting with named policies (feature rate-limit) |
marker | Conditional serialization with markers (feature marker) |
Re-exports§
pub use ctx::RequestCtx;pub use error::AFastError;pub use error::Error;pub use handler::DummyInvoker;pub use handler::Handler;pub use handler::EnumVariantMeta;pub use handler::FieldMeta;pub use handler::Structure;pub use handler::TagKind;pub use handler::TagMeta;pub use handler::ValidateRule;pub use handler::no_structure;pub use handler::HandlerEntry;pub use handler::HandlerInvoker;pub use handler::HandlerMeta;pub use handler::ParamMeta;pub use handler::Receiver;pub use handler::Sender;pub use service::Service;pub use state::StateMap;pub use app::AFast;pub use app::GenerateTarget;pub use app::JsTsCallType;pub use app::Lang;pub use app::NetCallType;
Modules§
- app
- Application builder, transport servers, and code generation.
- ctx
- Per-request context container.
- error
- Error types and error codes for the afast framework.
- handler
- Handler abstractions and metadata for the afast framework.
- marker
- Conditional serialization/deserialization with optional marker support.
- service
- Service container for grouping handlers into API namespaces.
- state
- Type-map for storing shared application state.
Macros§
- register
- Produces a
HandlerEntryfor the given handler function. - register_
ordinary - Produces an
OrdinaryHandlerDeffor the given ordinary HTTP handler. - register_
with_ path - Produces a
HandlerEntrywith a stable ID computed from the full handler path. - service
- Builds a
Servicewith handlers and nested groups.
Structs§
- Ctx
- Injects per-request context data into a handler.
- Custom
- Deserializes custom authentication or context data into
T. - Data
- Deserializes the binary request payload into
T. - State
- Injects shared application state into a handler.
Traits§
- AFast
Deserialize - 反序列化 trait,为类型提供从字节数组还原的能力。
- AFast
Serialize - 序列化 trait,为类型提供转换为字节数组的能力。
Functions§
- is_
standard_ header - Returns
trueif the given header name is in the standard set.
Type Aliases§
Attribute Macros§
- handler
- Marks an async function as a binary-protocol handler.
Derive Macros§
- AFast
Deserialize - Re-export derive 宏。
- AFast
Serialize - Re-export derive 宏。
- From
Form Data - Derives the
FromFormDatatrait for structs with named fields. - Tag
- Derives the
Structuretrait for a struct or enum.