1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-28 17:52:40 +01:00
actix-extras/examples/basics/src/main.rs

153 lines
4.8 KiB
Rust
Raw Normal View History

2017-10-22 04:35:50 +02:00
#![allow(unused_variables)]
2017-11-27 02:30:35 +01:00
#![cfg_attr(feature="cargo-clippy", allow(needless_pass_by_value))]
2017-10-22 04:35:50 +02:00
extern crate actix;
extern crate actix_web;
extern crate env_logger;
2017-11-03 21:35:34 +01:00
extern crate futures;
2017-12-19 09:18:57 +01:00
use futures::Stream;
2017-10-22 04:35:50 +02:00
2018-01-21 05:12:24 +01:00
use std::{io, env};
2017-10-22 04:35:50 +02:00
use actix_web::*;
2017-12-27 04:59:41 +01:00
use actix_web::middleware::RequestSession;
2017-11-30 23:42:20 +01:00
use futures::future::{FutureResult, result};
2018-01-06 01:32:36 +01:00
2018-01-06 16:43:59 +01:00
/// favicon handler
fn favicon(req: HttpRequest) -> Result<fs::NamedFile> {
Ok(fs::NamedFile::open("../static/favicon.ico")?)
}
2017-10-22 04:35:50 +02:00
2018-01-06 16:43:59 +01:00
/// simple index handler
2017-11-27 06:18:38 +01:00
fn index(mut req: HttpRequest) -> Result<HttpResponse> {
2017-10-22 04:35:50 +02:00
println!("{:?}", req);
2018-01-06 16:43:59 +01:00
// example of ...
if let Ok(ch) = req.poll() {
2017-12-19 09:18:57 +01:00
if let futures::Async::Ready(Some(d)) = ch {
println!("{}", String::from_utf8_lossy(d.as_ref()));
2017-11-06 10:24:49 +01:00
}
}
2017-11-27 02:30:35 +01:00
// session
2018-01-06 16:43:59 +01:00
let mut counter = 1;
2017-11-27 02:30:35 +01:00
if let Some(count) = req.session().get::<i32>("counter")? {
println!("SESSION value: {}", count);
2018-01-06 16:43:59 +01:00
counter = count + 1;
req.session().set("counter", counter)?;
2017-11-27 02:30:35 +01:00
} else {
2018-01-06 16:43:59 +01:00
req.session().set("counter", counter)?;
2017-11-27 02:30:35 +01:00
}
2018-01-06 16:43:59 +01:00
// html
let html = format!(r#"<!DOCTYPE html><html><head><title>actix - basics</title><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" /></head>
<body>
<h1>Welcome <img width="30px" height="30px" src="/static/actixLogo.png" /></h1>
session counter = {}
</body>
</html>"#, counter);
// response
Ok(HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body(&html).unwrap())
}
/// 404 handler
fn p404(req: HttpRequest) -> Result<HttpResponse> {
// html
2018-01-21 05:12:24 +01:00
let html = r#"<!DOCTYPE html><html><head><title>actix - basics</title><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" /></head>
2018-01-06 16:43:59 +01:00
<body>
<a href="index.html">back to home</a>
<h1>404</h1>
</body>
2018-01-21 05:12:24 +01:00
</html>"#;
2018-01-06 16:43:59 +01:00
// response
Ok(HttpResponse::build(StatusCode::NOT_FOUND)
.content_type("text/html; charset=utf-8")
2018-01-21 05:12:24 +01:00
.body(html).unwrap())
2017-10-22 04:35:50 +02:00
}
2018-01-06 16:43:59 +01:00
2017-11-28 01:41:37 +01:00
/// async handler
2017-11-30 23:42:20 +01:00
fn index_async(req: HttpRequest) -> FutureResult<HttpResponse, Error>
2017-11-03 21:35:34 +01:00
{
println!("{:?}", req);
2017-11-30 23:42:20 +01:00
result(HttpResponse::Ok()
.content_type("text/html")
.body(format!("Hello {}!", req.match_info().get("name").unwrap()))
.map_err(|e| e.into()))
2017-11-03 21:35:34 +01:00
}
2017-11-28 01:41:37 +01:00
/// handler with path parameters like `/user/{name}/`
2017-11-27 06:18:38 +01:00
fn with_param(req: HttpRequest) -> Result<HttpResponse>
2017-10-30 05:39:59 +01:00
{
2017-10-22 04:35:50 +02:00
println!("{:?}", req);
Ok(HttpResponse::Ok()
2017-10-30 05:39:59 +01:00
.content_type("test/plain")
.body(format!("Hello {}!", req.match_info().get("name").unwrap()))?)
2017-10-22 04:35:50 +02:00
}
fn main() {
2018-01-21 05:12:24 +01:00
env::set_var("RUST_LOG", "actix_web=debug");
env::set_var("RUST_BACKTRACE", "1");
env_logger::init();
2017-12-18 22:41:52 +01:00
let sys = actix::System::new("basic-example");
2017-10-22 04:35:50 +02:00
let addr = HttpServer::new(
|| Application::new()
// enable logger
2017-12-27 04:59:41 +01:00
.middleware(middleware::Logger::default())
2017-11-27 02:30:35 +01:00
// cookie session middleware
2017-12-27 04:59:41 +01:00
.middleware(middleware::SessionStorage::new(
middleware::CookieSessionBackend::build(&[0; 32])
2017-11-27 02:30:35 +01:00
.secure(false)
.finish()
))
2018-01-06 16:43:59 +01:00
// register favicon
.resource("/favicon.ico", |r| r.f(favicon))
2017-12-04 23:53:40 +01:00
// register simple route, handle all methods
.resource("/index.html", |r| r.f(index))
2017-12-02 08:32:15 +01:00
// with path parameters
.resource("/user/{name}/", |r| r.method(Method::GET).f(with_param))
2017-11-03 21:35:34 +01:00
// async handler
.resource("/async/{name}", |r| r.method(Method::GET).a(index_async))
.resource("/test", |r| r.f(|req| {
2017-11-29 22:26:55 +01:00
match *req.method() {
Method::GET => httpcodes::HTTPOk,
Method::POST => httpcodes::HTTPMethodNotAllowed,
_ => httpcodes::HTTPNotFound,
}
2017-12-04 23:53:40 +01:00
}))
2018-01-21 05:12:24 +01:00
.resource("/error.html", |r| r.f(|req| {
2018-03-19 00:27:34 +01:00
error::InternalError::new(
io::Error::new(io::ErrorKind::Other, "test"), StatusCode::OK)
2018-01-21 05:12:24 +01:00
}))
2017-10-22 04:35:50 +02:00
// static files
2018-01-03 04:37:33 +01:00
.handler("/static/", fs::StaticFiles::new("../static/", true))
2017-12-08 07:54:44 +01:00
// redirect
.resource("/", |r| r.method(Method::GET).f(|req| {
println!("{:?}", req);
2017-12-26 23:36:03 +01:00
HttpResponse::Found()
2017-12-08 07:54:44 +01:00
.header("LOCATION", "/index.html")
2017-12-21 01:32:31 +01:00
.finish()
2018-01-06 16:43:59 +01:00
}))
// default
.default_resource(|r| {
r.method(Method::GET).f(p404);
2018-03-03 07:08:56 +01:00
r.route().filter(pred::Not(pred::Get())).f(|req| httpcodes::HTTPMethodNotAllowed);
2018-01-06 16:43:59 +01:00
}))
.bind("127.0.0.1:8080").expect("Can not bind to 127.0.0.1:8080")
.shutdown_timeout(0) // <- Set shutdown timeout to 0 seconds (default 60s)
2017-12-19 18:08:36 +01:00
.start();
2017-10-22 04:35:50 +02:00
2017-12-19 18:51:28 +01:00
println!("Starting http server: 127.0.0.1:8080");
2017-10-22 04:35:50 +02:00
let _ = sys.run();
}