Skip to main content

Event

Struct Event 

Source
pub struct Event {
    pub inner: Arc<EventInner>,
    pub state: Option<Arc<dyn Any + Send + Sync>>,
    pub body: Bytes,
}
Expand description

Request event containing all request information

/ 包含所有请求信息的请求事件

The Event type provides lazy, cached access to request data through helper functions, avoiding the need for complex Axum extractor signatures.

Event 类型通过辅助函数提供延迟缓存的数据访问,无需复杂的 Axum 提取器签名。

§Cloning

§克隆

Event is cheap to clone because it uses Arc internally. Clones share the same inner data.

Event 克隆成本低,因为内部使用 Arc。克隆共享相同的内部数据。

§Thread Safety

§线程安全

Event can be safely shared between threads using Arc.

Event 可以使用 Arc 在线程间安全共享。

Fields§

§inner: Arc<EventInner>

Inner event data / 内部事件数据

§state: Option<Arc<dyn Any + Send + Sync>>

Application state (type-erased, stored as Arc<dyn Any + Send + Sync>) / 应用状态(类型擦除,存储为 Arc<dyn Any + Send + Sync>)

§body: Bytes

Request body bytes / 请求体字节数据

Implementations§

Source§

impl Event

Source

pub fn new( method: Method, path: String, raw_uri: Uri, headers: HeaderMap, params: HashMap<String, String>, query: HashMap<String, String>, body: Bytes, ) -> Self

Create a new Event with manual data

/ 使用手动数据创建新 Event

This function is typically called by the #[route] macro generated wrapper code.

此函数通常由 #[route] 宏生成的包装代码调用。

§Parameters
§参数
  • method - HTTP method / HTTP 方法
  • path - Request path / 请求路径
  • raw_uri - Original URI (for query parsing) / 原始 URI(用于查询解析)
  • headers - Request headers / 请求头
  • params - Path parameters / 路径参数
  • query - Query parameters / 查询参数
  • body - Request body bytes / 请求体字节数据
Source

pub fn method(&self) -> &Method

Get the HTTP method

/ 获取 HTTP 方法

§Example
§示例
if event.method() == Method::POST {
    // Handle POST request
}
Source

pub fn path(&self) -> &str

Get the request path

/ 获取请求路径

Returns the path part of the URI (without query string).

返回 URI 的路径部分(不含查询字符串)。

§Example
§示例
let path = event.path(); // "/users/123"
Source

pub fn uri(&self) -> &Uri

Get the original URI

/ 获取原始 URI

Returns the complete URI including path and query string.

返回完整的 URI,包括路径和查询字符串。

Source

pub fn headers(&self) -> &HeaderMap

Get request headers

/ 获取请求头

Returns a reference to the complete header map.

返回完整请求头的引用。

Source

pub fn params(&self) -> &HashMap<String, String>

Get path parameters (lazy cached)

/ 获取路径参数(延迟缓存)

Returns a reference to the path parameters map.

返回路径参数映射的引用。

Note: For more convenient access, use get_param or get_param_required.

注意:为了更方便的访问,请使用 get_paramget_param_required

Source

pub fn query(&self) -> &HashMap<String, String>

Get query parameters (lazy cached)

/ 获取查询参数(延迟缓存)

Query parameters are parsed from the URI on first access and cached.

查询参数在首次访问时从 URI 解析并缓存。

Note: For more convenient access, use get_query or get_query_param.

注意:为了更方便的访问,请使用 get_queryget_query_param

Source

pub fn state<T: Clone + Send + Sync + 'static>(&self) -> Option<T>

Get a value from the application state

/ 从应用状态获取值

§Type Parameters
§类型参数
  • T - The type to retrieve (must be Clone + Send + Sync + 'static) 要检索的类型(必须是 Clone + Send + Sync + 'static
§Example
§示例
use astrea::prelude::*;

struct DatabasePool {
    // ...
}

#[route]
async fn handler(event: Event) -> Result<Response> {
    let pool = event.state::<DatabasePool>()
        .ok_or_else(|| RouteError::internal("Database pool not found"))?;
    // Use pool...
}
Source

pub fn parse_json<T: DeserializeOwned>(&self, bytes: &[u8]) -> Result<T>

Parse JSON body from bytes

/ 从字节解析 JSON 请求体

This is a convenience method typically used by the generated wrapper code.

这是一个便捷方法,通常由生成的包装代码使用。

§Errors
§错误

Returns RouteError::BadRequest if the JSON is invalid.

如果 JSON 无效,返回 RouteError::BadRequest

§Example
§示例
#[derive(Deserialize)]
struct CreateUserRequest {
    name: String,
    email: String,
}

#[route]
async fn handler(event: Event, bytes: Bytes) -> Result<Response> {
    let body: CreateUserRequest = event.parse_json(&bytes)?;
    json(json!({ "message": format!("User {} created", body.name) }))
}
Source

pub fn parse_form<T: DeserializeOwned>(&self, bytes: &[u8]) -> Result<T>

Parse form data from bytes

/ 从字节解析表单数据

Parses URL-encoded form data from the request body.

从请求体解析 URL 编码的表单数据。

§Errors
§错误

Returns RouteError::BadRequest if the form data is invalid.

如果表单数据无效,返回 RouteError::BadRequest

§Example
§示例
#[derive(Deserialize)]
struct LoginForm {
    username: String,
    password: String,
}

#[route]
async fn handler(event: Event, bytes: Bytes) -> Result<Response> {
    let form: LoginForm = event.parse_form(&bytes)?;
    // Process login...
}
Source

pub fn parse_text(&self, bytes: &[u8]) -> Result<String>

Parse text body from bytes

/ 从字节解析文本请求体

Validates that the body is valid UTF-8.

验证请求体是有效的 UTF-8。

§Errors
§错误

Returns RouteError::BadRequest if the body is not valid UTF-8.

如果请求体不是有效的 UTF-8,返回 RouteError::BadRequest

Trait Implementations§

Source§

impl Clone for Event

Source§

fn clone(&self) -> Event

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Event

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !Freeze for Event

§

impl !RefUnwindSafe for Event

§

impl Send for Event

§

impl Sync for Event

§

impl Unpin for Event

§

impl UnsafeUnpin for Event

§

impl !UnwindSafe for Event

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,