1
0
mirror of https://github.com/actix/actix-extras.git synced 2025-02-02 10:59:03 +01:00

update examples

This commit is contained in:
Nikolay Kim 2017-11-29 14:03:18 -08:00
parent acc2fff655
commit ffb2e3c0ab
2 changed files with 31 additions and 42 deletions

View File

@ -9,12 +9,12 @@ use std::io::Read;
use actix_web::*; use actix_web::*;
/// somple handle /// somple handle
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> Result<HttpResponse> {
println!("{:?}", req); println!("{:?}", req);
httpcodes::HTTPOk Ok(httpcodes::HTTPOk
.build() .build()
.content_type("text/plain") .content_type("text/plain")
.body("Welcome!").unwrap() .body("Welcome!")?)
} }
fn main() { fn main() {
@ -37,10 +37,10 @@ fn main() {
.handler("/index.html", index) .handler("/index.html", index)
// with path parameters // with path parameters
.resource("/", |r| r.handler(Method::GET, |req| { .resource("/", |r| r.handler(Method::GET, |req| {
Ok(httpcodes::HTTPFound httpcodes::HTTPFound
.build() .build()
.header("LOCATION", "/index.html") .header("LOCATION", "/index.html")
.body(Body::Empty)?) .body(Body::Empty)
}))) })))
.serve_tls::<_, ()>("127.0.0.1:8080", pkcs12).unwrap(); .serve_tls::<_, ()>("127.0.0.1:8080", pkcs12).unwrap();

View File

@ -22,13 +22,23 @@ mod codec;
mod server; mod server;
mod session; mod session;
/// This is our websocket route state, this state is shared with all route instances /// This is our websocket route state, this state is shared with all route instances
/// via `HttpContext::state()` /// via `HttpContext::state()`
struct WsChatSessionState { struct WsChatSessionState {
addr: SyncAddress<server::ChatServer>, addr: SyncAddress<server::ChatServer>,
} }
/// Entry point for our route
fn chat_route(req: HttpRequest<WsChatSessionState>) -> Result<Reply> {
ws::start(
req,
WsChatSession {
id: 0,
hb: Instant::now(),
room: "Main".to_owned(),
name: None})
}
struct WsChatSession { struct WsChatSession {
/// unique session id /// unique session id
id: usize, id: usize,
@ -41,32 +51,12 @@ struct WsChatSession {
} }
impl Actor for WsChatSession { impl Actor for WsChatSession {
type Context = HttpContext<Self>; type Context = HttpContext<Self, WsChatSessionState>;
}
/// Entry point for our route
impl Route for WsChatSession {
type State = WsChatSessionState;
fn request(mut req: HttpRequest<WsChatSessionState>,
ctx: &mut HttpContext<Self>) -> RouteResult<Self>
{
// websocket handshakre, it may fail if request is not websocket request
let resp = ws::handshake(&req)?;
ctx.start(resp);
ctx.add_stream(ws::WsStream::new(&mut req));
Reply::async(
WsChatSession {
id: 0,
hb: Instant::now(),
room: "Main".to_owned(),
name: None})
}
} }
/// Handle messages from chat server, we simply send it to peer websocket /// Handle messages from chat server, we simply send it to peer websocket
impl Handler<session::Message> for WsChatSession { impl Handler<session::Message> for WsChatSession {
fn handle(&mut self, msg: session::Message, ctx: &mut HttpContext<Self>) fn handle(&mut self, msg: session::Message, ctx: &mut Self::Context)
-> Response<Self, session::Message> -> Response<Self, session::Message>
{ {
ws::WsWriter::text(ctx, &msg.0); ws::WsWriter::text(ctx, &msg.0);
@ -76,7 +66,7 @@ impl Handler<session::Message> for WsChatSession {
/// WebSocket message handler /// WebSocket message handler
impl Handler<ws::Message> for WsChatSession { impl Handler<ws::Message> for WsChatSession {
fn handle(&mut self, msg: ws::Message, ctx: &mut HttpContext<Self>) fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context)
-> Response<Self, ws::Message> -> Response<Self, ws::Message>
{ {
println!("WEBSOCKET MESSAGE: {:?}", msg); println!("WEBSOCKET MESSAGE: {:?}", msg);
@ -209,17 +199,16 @@ fn main() {
HttpServer::new( HttpServer::new(
Application::build("/", state) Application::build("/", state)
// redirect to websocket.html // redirect to websocket.html
.resource("/", |r| .resource("/", |r| r.handler(Method::GET, |req| {
r.handler(Method::GET, |req| { httpcodes::HTTPFound
Ok(httpcodes::HTTPFound .build()
.build() .header("LOCATION", "/static/websocket.html")
.header("LOCATION", "/static/websocket.html") .body(Body::Empty)
.body(Body::Empty)?) }))
}))
// websocket // websocket
.resource("/ws/", |r| r.get::<WsChatSession>()) .resource("/ws/", |r| r.get(chat_route))
// static resources // static resources
.route_handler("/static", StaticFiles::new("static/", true))) .route("/static", StaticFiles::new("static/", true)))
.serve::<_, ()>("127.0.0.1:8080").unwrap(); .serve::<_, ()>("127.0.0.1:8080").unwrap();
let _ = sys.run(); let _ = sys.run();