1
0
mirror of https://github.com/actix/examples synced 2025-06-28 09:50:36 +02:00

upgrade actix-web to 0.6

This commit is contained in:
Nikolay Kim
2018-05-08 11:08:43 -07:00
parent 27de52b5d5
commit bbeb262a5c
55 changed files with 689 additions and 518 deletions

View File

@ -7,5 +7,5 @@ workspace = "../"
[dependencies]
env_logger = "0.5"
actix = "0.5"
actix-web = "^0.5"
actix-web = "^0.6"
tera = "*"

View File

@ -4,28 +4,33 @@ extern crate env_logger;
#[macro_use]
extern crate tera;
use actix_web::{
http, error, middleware, server, App, HttpRequest, HttpResponse, Error};
use std::collections::HashMap;
use actix_web::{error, http, middleware, server, App, Error, HttpResponse, Query, State};
struct State {
template: tera::Tera, // <- store tera template in application state
struct AppState {
template: tera::Tera, // <- store tera template in application state
}
fn index(req: HttpRequest<State>) -> Result<HttpResponse, Error> {
let s = if let Some(name) = req.query().get("name") { // <- submitted form
fn index(
state: State<AppState>, query: Query<HashMap<String, String>>,
) -> Result<HttpResponse, Error> {
let s = if let Some(name) = query.get("name") {
// <- submitted form
let mut ctx = tera::Context::new();
ctx.add("name", &name.to_owned());
ctx.add("text", &"Welcome!".to_owned());
req.state().template.render("user.html", &ctx)
state
.template
.render("user.html", &ctx)
.map_err(|_| error::ErrorInternalServerError("Template error"))?
} else {
req.state().template.render("index.html", &tera::Context::new())
state
.template
.render("index.html", &tera::Context::new())
.map_err(|_| error::ErrorInternalServerError("Template error"))?
};
Ok(HttpResponse::Ok()
.content_type("text/html")
.body(s))
Ok(HttpResponse::Ok().content_type("text/html").body(s))
}
fn main() {
@ -34,13 +39,15 @@ fn main() {
let sys = actix::System::new("tera-example");
server::new(|| {
let tera = compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"));
let tera =
compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"));
App::with_state(State{template: tera})
App::with_state(AppState{template: tera})
// enable logger
.middleware(middleware::Logger::default())
.resource("/", |r| r.method(http::Method::GET).f(index))})
.bind("127.0.0.1:8080").unwrap()
.resource("/", |r| r.method(http::Method::GET).with2(index))
}).bind("127.0.0.1:8080")
.unwrap()
.start();
println!("Started http server: 127.0.0.1:8080");