1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-09-09 05:08:32 +00:00
actix-web/examples/basic.rs

54 lines
1.6 KiB
Rust
Raw Normal View History

2017-10-22 02:35:50 +00:00
#![allow(unused_variables)]
extern crate actix;
extern crate actix_web;
extern crate env_logger;
use actix_web::*;
/// somple handle
2017-10-23 00:33:24 +00:00
fn index(req: &mut HttpRequest, _payload: Payload, state: &()) -> HttpResponse {
2017-10-22 02:35:50 +00:00
println!("{:?}", req);
httpcodes::HTTPOk.into()
}
/// handle with path parameters like `/name/{name}/`
2017-10-30 04:39:59 +00:00
fn with_param(req: &mut HttpRequest, _payload: Payload, state: &())
-> HandlerResult<HttpResponse>
{
2017-10-22 02:35:50 +00:00
println!("{:?}", req);
2017-10-30 04:39:59 +00:00
Ok(HttpResponse::builder(StatusCode::OK)
.content_type("test/plain")
.body(format!("Hello {}!", req.match_info().get("name").unwrap()))?)
2017-10-22 02:35:50 +00:00
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
let _ = env_logger::init();
2017-10-22 02:35:50 +00:00
let sys = actix::System::new("ws-example");
HttpServer::new(
Application::default("/")
// enable logger
.middleware(Logger::new(None))
2017-10-22 02:35:50 +00:00
// register simple handler, handle all methods
.handler("/index.html", index)
// with path parameters
.resource("/user/{name}/", |r| r.handler(Method::GET, with_param))
// redirect
.resource("/", |r| r.handler(Method::GET, |req, _, _| {
println!("{:?}", req);
2017-10-30 04:39:59 +00:00
Ok(httpcodes::HTTPFound
.builder()
.header("LOCATION", "/index.html")
.body(Body::Empty)?)
2017-10-22 02:35:50 +00:00
}))
// static files
2017-10-26 13:12:23 +00:00
.route_handler("/static", StaticFiles::new("examples/static/", true)))
2017-10-22 02:35:50 +00:00
.serve::<_, ()>("127.0.0.1:8080").unwrap();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}