1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-26 19:41:12 +00:00

update basic example

This commit is contained in:
Nikolay Kim 2018-04-10 14:45:03 -07:00
parent 8dbbb0ee07
commit 50c2a5ceb0
2 changed files with 10 additions and 26 deletions

View file

@ -10,7 +10,7 @@ use futures::Stream;
use std::{io, env}; use std::{io, env};
use actix_web::{error, fs, pred, server, use actix_web::{error, fs, pred, server,
App, HttpRequest, HttpResponse, Result, Error}; App, HttpRequest, HttpResponse, Result, Error};
use actix_web::http::{Method, StatusCode}; use actix_web::http::{header, Method, StatusCode};
use actix_web::middleware::{self, RequestSession}; use actix_web::middleware::{self, RequestSession};
use futures::future::{FutureResult, result}; use futures::future::{FutureResult, result};
@ -40,36 +40,18 @@ fn index(mut req: HttpRequest) -> Result<HttpResponse> {
req.session().set("counter", counter)?; req.session().set("counter", counter)?;
} }
// 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 // response
Ok(HttpResponse::build(StatusCode::OK) Ok(HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8") .content_type("text/html; charset=utf-8")
.body(&html)) .body(include_str!("../static/welcome.html")))
} }
/// 404 handler /// 404 handler
fn p404(req: HttpRequest) -> Result<HttpResponse> { fn p404(req: HttpRequest) -> Result<fs::NamedFile> {
Ok(fs::NamedFile::open("./static/404.html")?
// html .set_status_code(StatusCode::NOT_FOUND))
let html = r#"<!DOCTYPE html><html><head><title>actix - basics</title><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" /></head>
<body>
<a href="index.html">back to home</a>
<h1>404</h1>
</body>
</html>"#;
// response
Ok(HttpResponse::build(StatusCode::NOT_FOUND)
.content_type("text/html; charset=utf-8")
.body(html))
} }
@ -131,14 +113,16 @@ fn main() {
// redirect // redirect
.resource("/", |r| r.method(Method::GET).f(|req| { .resource("/", |r| r.method(Method::GET).f(|req| {
println!("{:?}", req); println!("{:?}", req);
HttpResponse::Found() HttpResponse::Found()
.header("LOCATION", "/index.html") .header(header::LOCATION, "/index.html")
.finish() .finish()
})) }))
// default // default
.default_resource(|r| { .default_resource(|r| {
// 404 for GET request
r.method(Method::GET).f(p404); r.method(Method::GET).f(p404);
// all requests that are not `GET`
r.route().filter(pred::Not(pred::Get())).f( r.route().filter(pred::Not(pred::Get())).f(
|req| HttpResponse::MethodNotAllowed()); |req| HttpResponse::MethodNotAllowed());
})) }))

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.7 KiB

After

Width:  |  Height:  |  Size: 13 KiB