1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-24 07:53:00 +01:00
actix-extras/examples/basic.rs

76 lines
2.4 KiB
Rust
Raw Normal View History

2017-10-22 04:35:50 +02:00
#![allow(unused_variables)]
extern crate actix;
extern crate actix_web;
extern crate env_logger;
2017-11-03 21:35:34 +01:00
extern crate futures;
2017-10-22 04:35:50 +02:00
use actix_web::*;
2017-11-03 21:35:34 +01:00
use futures::stream::{once, Once};
2017-10-22 04:35:50 +02:00
/// somple handle
2017-11-06 10:24:49 +01:00
fn index(req: &mut HttpRequest, mut _payload: Payload, state: &()) -> HttpResponse {
2017-10-22 04:35:50 +02:00
println!("{:?}", req);
2017-11-06 10:24:49 +01:00
if let Ok(ch) = _payload.readany() {
if let futures::Async::Ready(Some(d)) = ch {
println!("{}", String::from_utf8_lossy(d.0.as_ref()));
}
}
2017-10-22 04:35:50 +02:00
httpcodes::HTTPOk.into()
}
2017-11-03 21:35:34 +01:00
/// somple handle
2017-11-16 07:06:28 +01:00
fn index_async(req: &mut HttpRequest, _payload: Payload, state: &())
-> Once<actix_web::Frame, actix_web::error::Error>
2017-11-03 21:35:34 +01:00
{
println!("{:?}", req);
once(Ok(HttpResponse::builder(StatusCode::OK)
.content_type("text/html")
.body(format!("Hello {}!", req.match_info().get("name").unwrap()))
.unwrap()
.into()))
}
2017-11-09 01:44:23 +01:00
/// handle with path parameters like `/user/{name}/`
2017-10-30 05:39:59 +01:00
fn with_param(req: &mut HttpRequest, _payload: Payload, state: &())
-> HandlerResult<HttpResponse>
{
2017-10-22 04:35:50 +02:00
println!("{:?}", req);
2017-10-30 05:39:59 +01:00
Ok(HttpResponse::builder(StatusCode::OK)
.content_type("test/plain")
.body(format!("Hello {}!", req.match_info().get("name").unwrap()))?)
2017-10-22 04:35:50 +02:00
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
let _ = env_logger::init();
2017-10-22 04:35:50 +02:00
let sys = actix::System::new("ws-example");
HttpServer::new(
Application::default("/")
// enable logger
2017-11-16 07:06:28 +01:00
//.middleware(middlewares::Logger::default())
2017-11-10 07:08:54 +01:00
// register simple handle r, handle all methods
2017-10-22 04:35:50 +02:00
.handler("/index.html", index)
// with path parameters
.resource("/user/{name}/", |r| r.handler(Method::GET, with_param))
2017-11-03 21:35:34 +01:00
// async handler
.resource("/async/{name}", |r| r.async(Method::GET, index_async))
2017-10-22 04:35:50 +02:00
// redirect
.resource("/", |r| r.handler(Method::GET, |req, _, _| {
println!("{:?}", req);
2017-10-30 05:39:59 +01:00
Ok(httpcodes::HTTPFound
.builder()
.header("LOCATION", "/index.html")
.body(Body::Empty)?)
2017-10-22 04:35:50 +02:00
}))
// static files
2017-10-26 15:12:23 +02:00
.route_handler("/static", StaticFiles::new("examples/static/", true)))
2017-10-22 04:35:50 +02:00
.serve::<_, ()>("127.0.0.1:8080").unwrap();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}