mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-01 00:44:26 +02:00
Improve documentation for actix-web-actors
(#2788)
This commit is contained in:
@ -14,6 +14,58 @@ use futures_core::Stream;
|
||||
use tokio::sync::oneshot::Sender;
|
||||
|
||||
/// Execution context for HTTP actors
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// A demonstration of [server-sent events](https://developer.mozilla.org/docs/Web/API/Server-sent_events) using actors:
|
||||
///
|
||||
/// ```no_run
|
||||
/// use std::time::Duration;
|
||||
///
|
||||
/// use actix::{Actor, AsyncContext};
|
||||
/// use actix_web::{get, http::header, App, HttpResponse, HttpServer};
|
||||
/// use actix_web_actors::HttpContext;
|
||||
/// use bytes::Bytes;
|
||||
///
|
||||
/// struct MyActor {
|
||||
/// count: usize,
|
||||
/// }
|
||||
///
|
||||
/// impl Actor for MyActor {
|
||||
/// type Context = HttpContext<Self>;
|
||||
///
|
||||
/// fn started(&mut self, ctx: &mut Self::Context) {
|
||||
/// ctx.run_later(Duration::from_millis(100), Self::write);
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// impl MyActor {
|
||||
/// fn write(&mut self, ctx: &mut HttpContext<Self>) {
|
||||
/// self.count += 1;
|
||||
/// if self.count > 3 {
|
||||
/// ctx.write_eof()
|
||||
/// } else {
|
||||
/// ctx.write(Bytes::from(format!("event: count\ndata: {}\n\n", self.count)));
|
||||
/// ctx.run_later(Duration::from_millis(100), Self::write);
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// #[get("/")]
|
||||
/// async fn index() -> HttpResponse {
|
||||
/// HttpResponse::Ok()
|
||||
/// .insert_header(header::ContentType(mime::TEXT_EVENT_STREAM))
|
||||
/// .streaming(HttpContext::create(MyActor { count: 0 }))
|
||||
/// }
|
||||
///
|
||||
/// #[actix_web::main]
|
||||
/// async fn main() -> std::io::Result<()> {
|
||||
/// HttpServer::new(|| App::new().service(index))
|
||||
/// .bind(("127.0.0.1", 8080))?
|
||||
/// .run()
|
||||
/// .await
|
||||
/// }
|
||||
/// ```
|
||||
pub struct HttpContext<A>
|
||||
where
|
||||
A: Actor<Context = HttpContext<A>>,
|
||||
@ -210,7 +262,7 @@ mod tests {
|
||||
type Context = HttpContext<Self>;
|
||||
|
||||
fn started(&mut self, ctx: &mut Self::Context) {
|
||||
ctx.run_later(Duration::from_millis(100), |slf, ctx| slf.write(ctx));
|
||||
ctx.run_later(Duration::from_millis(100), Self::write);
|
||||
}
|
||||
}
|
||||
|
||||
@ -221,7 +273,7 @@ mod tests {
|
||||
ctx.write_eof()
|
||||
} else {
|
||||
ctx.write(Bytes::from(format!("LINE-{}", self.count)));
|
||||
ctx.run_later(Duration::from_millis(100), |slf, ctx| slf.write(ctx));
|
||||
ctx.run_later(Duration::from_millis(100), Self::write);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user