1
0
mirror of https://github.com/actix/examples synced 2024-11-23 14:31:07 +01:00

update chat-broker example and fmt

This commit is contained in:
Nikolay Kim 2019-07-11 15:02:25 +06:00
parent 4aa663e794
commit 93275d7986
11 changed files with 51 additions and 61 deletions

View File

@ -37,6 +37,6 @@ members = [
"web-cors/backend",
"websocket",
"websocket-chat",
#"websocket-chat-broker",
"websocket-chat-broker",
"websocket-tcp-chat",
]

View File

@ -84,7 +84,7 @@ fn main() -> io::Result<()> {
App::new()
// cookie session middleware
.wrap(CookieSession::signed(&[0; 32]).secure(false))
// enable logger - always register actix-web Logger middleware last
// enable logger - always register actix-web Logger middleware last
.wrap(middleware::Logger::default())
// register favicon
.service(favicon)

View File

@ -27,7 +27,7 @@ fn main() -> std::io::Result<()> {
.name("auth-example")
.secure(false),
))
// enable logger - always register actix-web Logger middleware last
// enable logger - always register actix-web Logger middleware last
.wrap(middleware::Logger::default())
.service(web::resource("/login").route(web::post().to(login)))
.service(web::resource("/logout").to(logout))

View File

@ -13,41 +13,41 @@ use std::io;
#[derive(Debug, Serialize)]
struct Error {
msg: String,
status: u16,
msg: String,
status: u16,
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "{}", to_string_pretty(self).unwrap())
}
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "{}", to_string_pretty(self).unwrap())
}
}
impl ResponseError for Error {
// builds the actual response to send back when an error occurs
fn render_response(&self) -> HttpResponse {
let err_json = json!({ "error": self.msg });
HttpResponse::build(StatusCode::from_u16(self.status).unwrap()).json(err_json)
}
// builds the actual response to send back when an error occurs
fn render_response(&self) -> HttpResponse {
let err_json = json!({ "error": self.msg });
HttpResponse::build(StatusCode::from_u16(self.status).unwrap()).json(err_json)
}
}
fn index(_: HttpRequest) -> impl Future<Item = HttpResponse, Error = Error> {
err(Error {
msg: "an example error message".to_string(),
status: 400,
})
err(Error {
msg: "an example error message".to_string(),
status: 400,
})
}
fn main() -> io::Result<()> {
let sys = System::new("json_error_example");
let ip_address = "127.0.0.1:8000";
let sys = System::new("json_error_example");
let ip_address = "127.0.0.1:8000";
HttpServer::new(|| App::new().service(resource("/").route(get().to_async(index))))
.bind(ip_address)
.expect("Can not bind to port 8000")
.start();
HttpServer::new(|| App::new().service(resource("/").route(get().to_async(index))))
.bind(ip_address)
.expect("Can not bind to port 8000")
.start();
println!("Running server on {}", ip_address);
println!("Running server on {}", ip_address);
sys.run()
sys.run()
}

View File

@ -32,7 +32,8 @@ fn main() {
App::new()
.wrap(middleware::Logger::default())
.service(web::resource("/").route(web::post().to(index)))
}).bind("127.0.0.1:8081")
})
.bind("127.0.0.1:8081")
.unwrap()
.shutdown_timeout(1)
.start();

View File

@ -28,7 +28,7 @@ fn main() -> std::io::Result<()> {
App::new()
// redis session middleware
.wrap(RedisSession::new("127.0.0.1:6379", &[0; 32]))
// enable logger - always register actix-web Logger middleware last
// enable logger - always register actix-web Logger middleware last
.wrap(middleware::Logger::default())
// register simple route, handle all methods
.service(web::resource("/").to(index))

View File

@ -1,6 +1,6 @@
use actix::{Handler, Message};
use actix_web::{dev::Payload, Error, HttpRequest, FromRequest};
use actix_identity::Identity;
use actix_web::{dev::Payload, Error, FromRequest, HttpRequest};
use bcrypt::verify;
use diesel::prelude::*;

View File

@ -23,10 +23,7 @@ fn index(hb: web::Data<Handlebars>) -> HttpResponse {
}
#[get("/{user}/{data}")]
fn user(
hb: web::Data<Handlebars>,
info: web::Path<(String, String)>,
) -> HttpResponse {
fn user(hb: web::Data<Handlebars>, info: web::Path<(String, String)>) -> HttpResponse {
let data = json!({
"user": info.0,
"data": info.1

View File

@ -2,17 +2,20 @@
name = "websocket-broker-example"
version = "0.1.0"
authors = ["Chris Ricketts <chris.ricketts@steribar.com>"]
workspace = "../"
edition = "2018"
workspace = ".."
[[bin]]
name = "server"
path = "src/main.rs"
[dependencies]
rand = "*"
rand = "0.6"
futures = "0.1.24"
actix = "0.7"
actix-web = "0.7"
actix-broker = "0.1.4"
actix = "0.8.2"
actix-web = "1.0"
actix-files = "0.1"
actix-web-actors = "1.0"
actix-broker = "0.2.0"
log = "0.4.5"
simple_logger = "0.5.0"

View File

@ -1,24 +1,18 @@
#[macro_use]
extern crate actix;
extern crate actix_broker;
extern crate actix_web;
extern crate futures;
extern crate rand;
#[macro_use]
extern crate log;
extern crate simple_logger;
use actix::fut;
use actix::prelude::*;
use actix_broker::BrokerIssue;
use actix_web::server::HttpServer;
use actix_web::{fs, ws, App, Error, HttpRequest, HttpResponse};
use actix_files::Files;
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;
mod server;
use server::*;
fn chat_route(req: &HttpRequest<()>) -> Result<HttpResponse, Error> {
ws::start(req, WsChatSession::default())
fn chat_route(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
ws::start(WsChatSession::default(), &req, stream)
}
#[derive(Default)]
@ -34,7 +28,7 @@ impl WsChatSession {
// First send a leave message for the current room
let leave_msg = LeaveRoom(self.room.clone(), self.id);
// issue_sync comes from having the `BrokerIssue` trait in scope.
self.issue_sync(leave_msg, ctx);
self.issue_system_sync(leave_msg, ctx);
// Then send a join message for the new room
let join_msg = JoinRoom(
room_name.to_owned(),
@ -79,7 +73,7 @@ impl WsChatSession {
);
let msg = SendMessage(self.room.clone(), self.id, content);
// issue_async comes from having the `BrokerIssue` trait in scope.
self.issue_async(msg);
self.issue_system_async(msg);
}
}
@ -147,24 +141,19 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
}
}
fn main() {
fn main() -> std::io::Result<()> {
let sys = actix::System::new("websocket-broker-example");
simple_logger::init_with_level(log::Level::Info).unwrap();
HttpServer::new(move || {
App::new()
.resource("/ws/", |r| r.route().f(chat_route))
.handler(
"/",
fs::StaticFiles::new("./static/")
.unwrap()
.index_file("index.html"),
)
.service(web::resource("/ws/").to(chat_route))
.service(Files::new("/", "./static/").index_file("index.html"))
})
.bind("127.0.0.1:8080")
.unwrap()
.start();
info!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
sys.run()
}

View File

@ -81,8 +81,8 @@ impl Actor for WsChatServer {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
self.subscribe_async::<LeaveRoom>(ctx);
self.subscribe_async::<SendMessage>(ctx);
self.subscribe_system_async::<LeaveRoom>(ctx);
self.subscribe_system_async::<SendMessage>(ctx);
}
}