1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-12-24 09:00:34 +00:00

update examples

This commit is contained in:
Nikolay Kim 2018-03-30 18:54:38 -07:00
parent 9e751de707
commit 8d8f6bedad
19 changed files with 137 additions and 104 deletions

View file

@ -8,8 +8,10 @@ extern crate futures;
use futures::Stream; use futures::Stream;
use std::{io, env}; use std::{io, env};
use actix_web::*; use actix_web::{error, fs, pred,
use actix_web::middleware::RequestSession; Application, HttpRequest, HttpResponse, HttpServer, Result, Error};
use actix_web::http::{Method, StatusCode};
use actix_web::middleware::{self, RequestSession};
use futures::future::{FutureResult, result}; use futures::future::{FutureResult, result};
/// favicon handler /// favicon handler
@ -118,9 +120,9 @@ fn main() {
.resource("/async/{name}", |r| r.method(Method::GET).a(index_async)) .resource("/async/{name}", |r| r.method(Method::GET).a(index_async))
.resource("/test", |r| r.f(|req| { .resource("/test", |r| r.f(|req| {
match *req.method() { match *req.method() {
Method::GET => httpcodes::HTTPOk, Method::GET => HttpResponse::Ok(),
Method::POST => httpcodes::HTTPMethodNotAllowed, Method::POST => HttpResponse::MethodNotAllowed(),
_ => httpcodes::HTTPNotFound, _ => HttpResponse::NotFound(),
} }
})) }))
.resource("/error.html", |r| r.f(|req| { .resource("/error.html", |r| r.f(|req| {
@ -140,7 +142,8 @@ fn main() {
// default // default
.default_resource(|r| { .default_resource(|r| {
r.method(Method::GET).f(p404); r.method(Method::GET).f(p404);
r.route().filter(pred::Not(pred::Get())).f(|req| httpcodes::HTTPMethodNotAllowed); r.route().filter(pred::Not(pred::Get())).f(
|req| HttpResponse::MethodNotAllowed());
})) }))
.bind("127.0.0.1:8080").expect("Can not bind to 127.0.0.1:8080") .bind("127.0.0.1:8080").expect("Can not bind to 127.0.0.1:8080")

View file

@ -16,8 +16,9 @@ extern crate actix;
extern crate actix_web; extern crate actix_web;
extern crate env_logger; extern crate env_logger;
use actix::*; use actix::prelude::*;
use actix_web::*; use actix_web::{http, middleware,
Application, HttpServer, HttpRequest, HttpResponse, Error, AsyncResponder};
use diesel::prelude::*; use diesel::prelude::*;
use futures::future::Future; use futures::future::Future;
@ -43,8 +44,8 @@ fn index(req: HttpRequest<State>) -> Box<Future<Item=HttpResponse, Error=Error>>
.from_err() .from_err()
.and_then(|res| { .and_then(|res| {
match res { match res {
Ok(user) => Ok(httpcodes::HTTPOk.build().json(user)?), Ok(user) => Ok(HttpResponse::Ok().json(user)?),
Err(_) => Ok(httpcodes::HTTPInternalServerError.into()) Err(_) => Ok(HttpResponse::InternalServerError().into())
} }
}) })
.responder() .responder()
@ -65,7 +66,7 @@ fn main() {
Application::with_state(State{db: addr.clone()}) Application::with_state(State{db: addr.clone()})
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/{name}", |r| r.method(Method::GET).a(index))}) .resource("/{name}", |r| r.method(http::Method::GET).a(index))})
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()
.start(); .start();

View file

@ -2,7 +2,7 @@ extern crate actix;
extern crate actix_web; extern crate actix_web;
extern crate env_logger; extern crate env_logger;
use actix_web::*; use actix_web::{Application, HttpRequest, server, middleware};
fn index(_req: HttpRequest) -> &'static str { fn index(_req: HttpRequest) -> &'static str {
@ -14,7 +14,7 @@ fn main() {
let _ = env_logger::init(); let _ = env_logger::init();
let sys = actix::System::new("ws-example"); let sys = actix::System::new("ws-example");
let _addr = HttpServer::new( let _addr = server::new(
|| Application::new() || Application::new()
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())

View file

@ -3,23 +3,24 @@ extern crate actix_web;
extern crate futures; extern crate futures;
extern crate env_logger; extern crate env_logger;
use actix_web::*;
use futures::{Future, Stream}; use futures::{Future, Stream};
use actix_web::{client, server, middleware,
Application, AsyncResponder, Body,
HttpRequest, HttpResponse, HttpMessage, Error};
/// Stream client request response and then send body to a server response /// Stream client request response and then send body to a server response
fn index(_req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> { fn index(_req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
client::ClientRequest::get("https://www.rust-lang.org/en-US/") client::ClientRequest::get("https://www.rust-lang.org/en-US/")
.finish().unwrap() .finish().unwrap()
.send() .send()
.map_err(error::Error::from) // <- convert SendRequestError to an Error .map_err(Error::from) // <- convert SendRequestError to an Error
.and_then( .and_then(
|resp| resp.body() // <- this is MessageBody type, resolves to complete body |resp| resp.body() // <- this is MessageBody type, resolves to complete body
.from_err() // <- convert PayloadError to a Error .from_err() // <- convert PayloadError to a Error
.and_then(|body| { // <- we got complete body, now send as server response .and_then(|body| { // <- we got complete body, now send as server response
httpcodes::HttpOk.build() HttpResponse::Ok()
.body(body) .body(body)
.map_err(error::Error::from) .map_err(Error::from)
})) }))
.responder() .responder()
} }
@ -30,9 +31,9 @@ fn streaming(_req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
client::ClientRequest::get("https://www.rust-lang.org/en-US/") client::ClientRequest::get("https://www.rust-lang.org/en-US/")
.finish().unwrap() .finish().unwrap()
.send() // <- connect to host and send request .send() // <- connect to host and send request
.map_err(error::Error::from) // <- convert SendRequestError to an Error .map_err(Error::from) // <- convert SendRequestError to an Error
.and_then(|resp| { // <- we received client response .and_then(|resp| { // <- we received client response
httpcodes::HttpOk.build() HttpResponse::Ok()
// read one chunk from client response and send this chunk to a server response // read one chunk from client response and send this chunk to a server response
// .from_err() converts PayloadError to a Error // .from_err() converts PayloadError to a Error
.body(Body::Streaming(Box::new(resp.from_err()))) .body(Body::Streaming(Box::new(resp.from_err())))
@ -46,7 +47,7 @@ fn main() {
env_logger::init(); env_logger::init();
let sys = actix::System::new("http-proxy"); let sys = actix::System::new("http-proxy");
let _addr = HttpServer::new( let _addr = server::new(
|| Application::new() || Application::new()
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/streaming", |r| r.f(streaming)) .resource("/streaming", |r| r.f(streaming))

View file

@ -7,7 +7,9 @@ extern crate serde_json;
#[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_derive;
#[macro_use] extern crate json; #[macro_use] extern crate json;
use actix_web::*; use actix_web::{middleware, http, error, server,
Application, AsyncResponder,
HttpRequest, HttpResponse, HttpMessage, Error, Json};
use bytes::BytesMut; use bytes::BytesMut;
use futures::{Future, Stream}; use futures::{Future, Stream};
@ -25,15 +27,15 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
.from_err() // convert all errors into `Error` .from_err() // convert all errors into `Error`
.and_then(|val: MyObj| { .and_then(|val: MyObj| {
println!("model: {:?}", val); println!("model: {:?}", val);
Ok(httpcodes::HTTPOk.build().json(val)?) // <- send response Ok(HttpResponse::Ok().json(val)?) // <- send response
}) })
.responder() .responder()
} }
/// This handler uses `With` helper for loading serde json object. /// This handler uses `With` helper for loading serde json object.
fn extract_item(item: Json<MyObj>) -> Result<HttpResponse> { fn extract_item(item: Json<MyObj>) -> Result<HttpResponse, Error> {
println!("model: {:?}", &item); println!("model: {:?}", &item);
httpcodes::HTTPOk.build().json(item.0) // <- send response HttpResponse::Ok().json(item.0) // <- send response
} }
const MAX_SIZE: usize = 262_144; // max payload size is 256k const MAX_SIZE: usize = 262_144; // max payload size is 256k
@ -62,7 +64,7 @@ fn index_manual(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>>
.and_then(|body| { .and_then(|body| {
// body is loaded, now we can deserialize serde-json // body is loaded, now we can deserialize serde-json
let obj = serde_json::from_slice::<MyObj>(&body)?; let obj = serde_json::from_slice::<MyObj>(&body)?;
Ok(httpcodes::HTTPOk.build().json(obj)?) // <- send response Ok(HttpResponse::Ok().json(obj)?) // <- send response
}) })
.responder() .responder()
} }
@ -75,7 +77,7 @@ fn index_mjsonrust(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Erro
// body is loaded, now we can deserialize json-rust // body is loaded, now we can deserialize json-rust
let result = json::parse(std::str::from_utf8(&body).unwrap()); // return Result let result = json::parse(std::str::from_utf8(&body).unwrap()); // return Result
let injson: JsonValue = match result { Ok(v) => v, Err(e) => object!{"err" => e.to_string() } }; let injson: JsonValue = match result { Ok(v) => v, Err(e) => object!{"err" => e.to_string() } };
Ok(HttpResponse::build(StatusCode::OK) Ok(HttpResponse::Ok()
.content_type("application/json") .content_type("application/json")
.body(injson.dump()).unwrap()) .body(injson.dump()).unwrap())
}) })
@ -87,15 +89,15 @@ fn main() {
let _ = env_logger::init(); let _ = env_logger::init();
let sys = actix::System::new("json-example"); let sys = actix::System::new("json-example");
let addr = HttpServer::new(|| { let _ = server::new(|| {
Application::new() Application::new()
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/extractor/{name}/{number}/", .resource("/extractor/{name}/{number}/",
|r| r.method(Method::GET).with(extract_item)) |r| r.method(http::Method::GET).with(extract_item))
.resource("/manual", |r| r.method(Method::POST).f(index_manual)) .resource("/manual", |r| r.method(http::Method::POST).f(index_manual))
.resource("/mjsonrust", |r| r.method(Method::POST).f(index_mjsonrust)) .resource("/mjsonrust", |r| r.method(http::Method::POST).f(index_mjsonrust))
.resource("/", |r| r.method(Method::POST).f(index))}) .resource("/", |r| r.method(http::Method::POST).f(index))})
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()
.shutdown_timeout(1) .shutdown_timeout(1)
.start(); .start();

View file

@ -12,8 +12,10 @@ extern crate actix;
extern crate actix_web; extern crate actix_web;
extern crate env_logger; extern crate env_logger;
use actix::*; use actix::prelude::*;
use actix_web::*; use actix_web::{middleware, http, server,
Application, AsyncResponder,
HttpRequest, HttpResponse, HttpMessage, Error};
use juniper::http::graphiql::graphiql_source; use juniper::http::graphiql::graphiql_source;
use juniper::http::GraphQLRequest; use juniper::http::GraphQLRequest;
@ -61,9 +63,9 @@ impl Handler<GraphQLData> for GraphQLExecutor {
} }
} }
fn graphiql(_req: HttpRequest<State>) -> Result<HttpResponse> { fn graphiql(_req: HttpRequest<State>) -> Result<HttpResponse, Error> {
let html = graphiql_source("http://127.0.0.1:8080/graphql"); let html = graphiql_source("http://127.0.0.1:8080/graphql");
Ok(HttpResponse::build(StatusCode::OK) Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8") .content_type("text/html; charset=utf-8")
.body(html).unwrap()) .body(html).unwrap())
} }
@ -77,8 +79,8 @@ fn graphql(req: HttpRequest<State>) -> Box<Future<Item=HttpResponse, Error=Error
.from_err() .from_err()
.and_then(|res| { .and_then(|res| {
match res { match res {
Ok(user) => Ok(httpcodes::HTTPOk.build().body(user)?), Ok(user) => Ok(HttpResponse::Ok().body(user)?),
Err(_) => Ok(httpcodes::HTTPInternalServerError.into()) Err(_) => Ok(HttpResponse::InternalServerError().into())
} }
}) })
}) })
@ -96,12 +98,12 @@ fn main() {
}); });
// Start http server // Start http server
let _addr = HttpServer::new(move || { let _ = server::new(move || {
Application::with_state(State{executor: addr.clone()}) Application::with_state(State{executor: addr.clone()})
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/graphql", |r| r.method(Method::POST).a(graphql)) .resource("/graphql", |r| r.method(http::Method::POST).h(graphql))
.resource("/graphiql", |r| r.method(Method::GET).f(graphiql))}) .resource("/graphiql", |r| r.method(http::Method::GET).h(graphiql))})
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()
.start(); .start();

View file

@ -5,7 +5,9 @@ extern crate env_logger;
extern crate futures; extern crate futures;
use actix::*; use actix::*;
use actix_web::*; use actix_web::{
http, middleware, multipart, server,
Application, AsyncResponder, HttpRequest, HttpResponse, HttpMessage, Error};
use futures::{Future, Stream}; use futures::{Future, Stream};
use futures::future::{result, Either}; use futures::future::{result, Either};
@ -38,7 +40,7 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>>
} }
}) })
.finish() // <- Stream::finish() combinator from actix .finish() // <- Stream::finish() combinator from actix
.map(|_| httpcodes::HTTPOk.into()) .map(|_| HttpResponse::Ok().into())
.responder() .responder()
} }
@ -47,10 +49,10 @@ fn main() {
let _ = env_logger::init(); let _ = env_logger::init();
let sys = actix::System::new("multipart-example"); let sys = actix::System::new("multipart-example");
let addr = HttpServer::new( let _ = server::new(
|| Application::new() || Application::new()
.middleware(middleware::Logger::default()) // <- logger .middleware(middleware::Logger::default()) // <- logger
.resource("/multipart", |r| r.method(Method::POST).a(index))) .resource("/multipart", |r| r.method(http::Method::POST).a(index)))
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()
.start(); .start();

View file

@ -9,8 +9,10 @@ extern crate prost;
#[macro_use] #[macro_use]
extern crate prost_derive; extern crate prost_derive;
use actix_web::*;
use futures::Future; use futures::Future;
use actix_web::{
http, middleware, server,
Application, AsyncResponder, HttpRequest, HttpResponse, Error};
mod protobuf; mod protobuf;
use protobuf::ProtoBufResponseBuilder; use protobuf::ProtoBufResponseBuilder;
@ -31,7 +33,7 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
.from_err() // convert all errors into `Error` .from_err() // convert all errors into `Error`
.and_then(|val: MyObj| { .and_then(|val: MyObj| {
println!("model: {:?}", val); println!("model: {:?}", val);
Ok(httpcodes::HTTPOk.build().protobuf(val)?) // <- send response Ok(HttpResponse::Ok().protobuf(val)?) // <- send response
}) })
.responder() .responder()
} }
@ -39,13 +41,13 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
fn main() { fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info"); ::std::env::set_var("RUST_LOG", "actix_web=info");
let _ = env_logger::init(); env_logger::init();
let sys = actix::System::new("protobuf-example"); let sys = actix::System::new("protobuf-example");
let addr = HttpServer::new(|| { let _ = server::new(|| {
Application::new() Application::new()
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/", |r| r.method(Method::POST).f(index))}) .resource("/", |r| r.method(http::Method::POST).f(index))})
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()
.shutdown_timeout(1) .shutdown_timeout(1)
.start(); .start();

View file

@ -6,7 +6,7 @@ use prost::Message;
use prost::DecodeError as ProtoBufDecodeError; use prost::DecodeError as ProtoBufDecodeError;
use prost::EncodeError as ProtoBufEncodeError; use prost::EncodeError as ProtoBufEncodeError;
use actix_web::header::http::{CONTENT_TYPE, CONTENT_LENGTH}; use actix_web::http::header::{CONTENT_TYPE, CONTENT_LENGTH};
use actix_web::{Responder, HttpMessage, HttpRequest, HttpResponse}; use actix_web::{Responder, HttpMessage, HttpRequest, HttpResponse};
use actix_web::dev::HttpResponseBuilder; use actix_web::dev::HttpResponseBuilder;
use actix_web::error::{Error, PayloadError, ResponseError}; use actix_web::error::{Error, PayloadError, ResponseError};

View file

@ -10,8 +10,10 @@ extern crate r2d2;
extern crate r2d2_sqlite; extern crate r2d2_sqlite;
extern crate rusqlite; extern crate rusqlite;
use actix::*; use actix::prelude::*;
use actix_web::*; use actix_web::{
middleware, http, server,
Application, AsyncResponder, HttpRequest, HttpResponse, Error};
use futures::future::Future; use futures::future::Future;
use r2d2_sqlite::SqliteConnectionManager; use r2d2_sqlite::SqliteConnectionManager;
@ -32,8 +34,8 @@ fn index(req: HttpRequest<State>) -> Box<Future<Item=HttpResponse, Error=Error>>
.from_err() .from_err()
.and_then(|res| { .and_then(|res| {
match res { match res {
Ok(user) => Ok(httpcodes::HTTPOk.build().json(user)?), Ok(user) => Ok(HttpResponse::Ok().json(user)?),
Err(_) => Ok(httpcodes::HTTPInternalServerError.into()) Err(_) => Ok(HttpResponse::InternalServerError().into())
} }
}) })
.responder() .responder()
@ -41,7 +43,7 @@ fn index(req: HttpRequest<State>) -> Box<Future<Item=HttpResponse, Error=Error>>
fn main() { fn main() {
::std::env::set_var("RUST_LOG", "actix_web=debug"); ::std::env::set_var("RUST_LOG", "actix_web=debug");
let _ = env_logger::init(); env_logger::init();
let sys = actix::System::new("r2d2-example"); let sys = actix::System::new("r2d2-example");
// r2d2 pool // r2d2 pool
@ -52,11 +54,11 @@ fn main() {
let addr = SyncArbiter::start(3, move || DbExecutor(pool.clone())); let addr = SyncArbiter::start(3, move || DbExecutor(pool.clone()));
// Start http server // Start http server
let _addr = HttpServer::new(move || { let _ = server::new(move || {
Application::with_state(State{db: addr.clone()}) Application::with_state(State{db: addr.clone()})
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/{name}", |r| r.method(Method::GET).a(index))}) .resource("/{name}", |r| r.method(http::Method::GET).a(index))})
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()
.start(); .start();

View file

@ -9,8 +9,10 @@ extern crate env_logger;
use std::cell::Cell; use std::cell::Cell;
use actix::*; use actix::prelude::*;
use actix_web::*; use actix_web::{
http, server, ws, middleware,
Application, HttpRequest, HttpResponse, Error};
/// Application state /// Application state
struct AppState { struct AppState {
@ -18,12 +20,11 @@ struct AppState {
} }
/// simple handle /// simple handle
fn index(req: HttpRequest<AppState>) -> HttpResponse { fn index(req: HttpRequest<AppState>) -> Result<HttpResponse, Error> {
println!("{:?}", req); println!("{:?}", req);
req.state().counter.set(req.state().counter.get() + 1); req.state().counter.set(req.state().counter.get() + 1);
httpcodes::HTTPOk.with_body( HttpResponse::Ok().body(format!("Num of requests: {}", req.state().counter.get()))
format!("Num of requests: {}", req.state().counter.get()))
} }
/// `MyWebSocket` counts how many messages it receives from peer, /// `MyWebSocket` counts how many messages it receives from peer,
@ -58,14 +59,15 @@ fn main() {
let _ = env_logger::init(); let _ = env_logger::init();
let sys = actix::System::new("ws-example"); let sys = actix::System::new("ws-example");
let addr = HttpServer::new( let _ = server::new(
|| Application::with_state(AppState{counter: Cell::new(0)}) || Application::with_state(AppState{counter: Cell::new(0)})
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
// websocket route // websocket route
.resource( .resource(
"/ws/", |r| "/ws/", |r|
r.method(Method::GET).f(|req| ws::start(req, MyWebSocket{counter: 0}))) r.method(http::Method::GET).f(
|req| ws::start(req, MyWebSocket{counter: 0})))
// register simple handler, handle all methods // register simple handler, handle all methods
.resource("/", |r| r.f(index))) .resource("/", |r| r.f(index)))
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()

View file

@ -4,14 +4,17 @@ extern crate env_logger;
#[macro_use] #[macro_use]
extern crate tera; extern crate tera;
use actix_web::*; use actix_web::{
http, error, middleware, server,
Application, HttpRequest, HttpResponse, Error,
};
struct State { struct State {
template: tera::Tera, // <- store tera template in application state template: tera::Tera, // <- store tera template in application state
} }
fn index(req: HttpRequest<State>) -> Result<HttpResponse> { fn index(req: HttpRequest<State>) -> Result<HttpResponse, Error> {
let s = if let Some(name) = req.query().get("name") { // <- submitted form let s = if let Some(name) = req.query().get("name") { // <- submitted form
let mut ctx = tera::Context::new(); let mut ctx = tera::Context::new();
ctx.add("name", &name.to_owned()); ctx.add("name", &name.to_owned());
@ -22,7 +25,7 @@ fn index(req: HttpRequest<State>) -> Result<HttpResponse> {
req.state().template.render("index.html", &tera::Context::new()) req.state().template.render("index.html", &tera::Context::new())
.map_err(|_| error::ErrorInternalServerError("Template error"))? .map_err(|_| error::ErrorInternalServerError("Template error"))?
}; };
Ok(httpcodes::HTTPOk.build() Ok(HttpResponse::Ok()
.content_type("text/html") .content_type("text/html")
.body(s)?) .body(s)?)
} }
@ -32,13 +35,13 @@ fn main() {
let _ = env_logger::init(); let _ = env_logger::init();
let sys = actix::System::new("tera-example"); let sys = actix::System::new("tera-example");
let addr = HttpServer::new(|| { let _ = server::new(|| {
let tera = compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")); let tera = compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"));
Application::with_state(State{template: tera}) Application::with_state(State{template: tera})
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/", |r| r.method(Method::GET).f(index))}) .resource("/", |r| r.method(http::Method::GET).f(index))})
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()
.start(); .start();

View file

@ -4,15 +4,16 @@ extern crate actix_web;
extern crate env_logger; extern crate env_logger;
extern crate openssl; extern crate openssl;
use actix_web::*;
use openssl::ssl::{SslMethod, SslAcceptor, SslFiletype}; use openssl::ssl::{SslMethod, SslAcceptor, SslFiletype};
use actix_web::{
http, middleware, server,
Application, HttpRequest, HttpResponse, Error};
/// simple handle /// simple handle
fn index(req: HttpRequest) -> Result<HttpResponse> { fn index(req: HttpRequest) -> Result<HttpResponse, Error> {
println!("{:?}", req); println!("{:?}", req);
Ok(httpcodes::HTTPOk Ok(HttpResponse::Ok()
.build()
.content_type("text/plain") .content_type("text/plain")
.body("Welcome!")?) .body("Welcome!")?)
} }
@ -21,7 +22,7 @@ fn main() {
if ::std::env::var("RUST_LOG").is_err() { if ::std::env::var("RUST_LOG").is_err() {
::std::env::set_var("RUST_LOG", "actix_web=info"); ::std::env::set_var("RUST_LOG", "actix_web=info");
} }
let _ = env_logger::init(); env_logger::init();
let sys = actix::System::new("ws-example"); let sys = actix::System::new("ws-example");
// load ssl keys // load ssl keys
@ -29,18 +30,17 @@ fn main() {
builder.set_private_key_file("key.pem", SslFiletype::PEM).unwrap(); builder.set_private_key_file("key.pem", SslFiletype::PEM).unwrap();
builder.set_certificate_chain_file("cert.pem").unwrap(); builder.set_certificate_chain_file("cert.pem").unwrap();
let addr = HttpServer::new( let _ = server::new(
|| Application::new() || Application::new()
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
// register simple handler, handle all methods // register simple handler, handle all methods
.resource("/index.html", |r| r.f(index)) .resource("/index.html", |r| r.f(index))
// with path parameters // with path parameters
.resource("/", |r| r.method(Method::GET).f(|req| { .resource("/", |r| r.method(http::Method::GET).f(|req| {
httpcodes::HTTPFound HttpResponse::Found()
.build()
.header("LOCATION", "/index.html") .header("LOCATION", "/index.html")
.body(Body::Empty) .finish()
}))) })))
.bind("127.0.0.1:8443").unwrap() .bind("127.0.0.1:8443").unwrap()
.start_ssl(builder).unwrap(); .start_ssl(builder).unwrap();

View file

@ -5,12 +5,11 @@ extern crate futures;
extern crate actix; extern crate actix;
extern crate actix_web; extern crate actix_web;
extern crate env_logger; extern crate env_logger;
extern crate http;
use std::env; use std::env;
use http::header; use actix_web::{
use actix_web::*; http, middleware, server,
use actix_web::middleware::cors; Application};
mod user; mod user;
use user::info; use user::info;
@ -22,20 +21,21 @@ fn main() {
let sys = actix::System::new("Actix-web-CORS"); let sys = actix::System::new("Actix-web-CORS");
HttpServer::new( server::new(
|| Application::new() || Application::new()
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/user/info", |r| { .resource("/user/info", |r| {
cors::Cors::build() middleware::cors::Cors::build()
.allowed_origin("http://localhost:1234") .allowed_origin("http://localhost:1234")
.allowed_methods(vec!["GET", "POST"]) .allowed_methods(vec!["GET", "POST"])
.allowed_headers( .allowed_headers(
vec![header::AUTHORIZATION, vec![http::header::AUTHORIZATION,
header::ACCEPT, header::CONTENT_TYPE]) http::header::ACCEPT,
http::header::CONTENT_TYPE])
.max_age(3600) .max_age(3600)
.finish().expect("Can not create CORS middleware") .finish().expect("Can not create CORS middleware")
.register(r); .register(r);
r.method(Method::POST).a(info); r.method(http::Method::POST).a(info);
})) }))
.bind("127.0.0.1:8000").unwrap() .bind("127.0.0.1:8000").unwrap()
.shutdown_timeout(200) .shutdown_timeout(200)

View file

@ -14,6 +14,6 @@ pub fn info(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
req.json() req.json()
.from_err() .from_err()
.and_then(|res: Info| { .and_then(|res: Info| {
Ok(httpcodes::HTTPOk.build().json(res)?) Ok(httpcodes::HttpOk.build().json(res)?)
}).responder() }).responder()
} }

View file

@ -17,7 +17,9 @@ extern crate actix_web;
use std::time::Instant; use std::time::Instant;
use actix::*; use actix::*;
use actix_web::*; use actix_web::{
http, fs, ws,
Application, HttpRequest, HttpResponse, HttpServer, Error};
mod codec; mod codec;
mod server; mod server;
@ -30,7 +32,7 @@ struct WsChatSessionState {
} }
/// Entry point for our route /// Entry point for our route
fn chat_route(req: HttpRequest<WsChatSessionState>) -> Result<HttpResponse> { fn chat_route(req: HttpRequest<WsChatSessionState>) -> Result<HttpResponse, Error> {
ws::start( ws::start(
req, req,
WsChatSession { WsChatSession {
@ -190,9 +192,8 @@ fn main() {
Application::with_state(state) Application::with_state(state)
// redirect to websocket.html // redirect to websocket.html
.resource("/", |r| r.method(Method::GET).f(|_| { .resource("/", |r| r.method(http::Method::GET).f(|_| {
httpcodes::HTTPFound HttpResponse::Found()
.build()
.header("LOCATION", "/static/websocket.html") .header("LOCATION", "/static/websocket.html")
.finish() .finish()
})) }))

View file

@ -8,11 +8,14 @@ extern crate actix;
extern crate actix_web; extern crate actix_web;
extern crate env_logger; extern crate env_logger;
use actix::*; use actix::prelude::*;
use actix_web::*; use actix_web::{
http, middleware, server, fs, ws,
Application, HttpRequest, HttpResponse, Error,
};
/// do websocket handshake and start `MyWebSocket` actor /// do websocket handshake and start `MyWebSocket` actor
fn ws_index(r: HttpRequest) -> Result<HttpResponse> { fn ws_index(r: HttpRequest) -> Result<HttpResponse, Error> {
ws::start(r, MyWebSocket) ws::start(r, MyWebSocket)
} }
@ -47,12 +50,12 @@ fn main() {
let _ = env_logger::init(); let _ = env_logger::init();
let sys = actix::System::new("ws-example"); let sys = actix::System::new("ws-example");
let _addr = HttpServer::new( server::new(
|| Application::new() || Application::new()
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
// websocket route // websocket route
.resource("/ws/", |r| r.method(Method::GET).f(ws_index)) .resource("/ws/", |r| r.method(http::Method::GET).f(ws_index))
// static files // static files
.handler("/", fs::StaticFiles::new("../static/", true) .handler("/", fs::StaticFiles::new("../static/", true)
.index_file("index.html"))) .index_file("index.html")))

View file

@ -35,7 +35,7 @@ use httpresponse::HttpResponse;
/// # #[macro_use] extern crate serde_derive; /// # #[macro_use] extern crate serde_derive;
/// # use actix_web::*; /// # use actix_web::*;
/// use actix_web::http::NormalizePath; /// use actix_web::http::NormalizePath;
/// # ///
/// # fn index(req: HttpRequest) -> httpcodes::StaticResponse { /// # fn index(req: HttpRequest) -> httpcodes::StaticResponse {
/// # httpcodes::HttpOk /// # httpcodes::HttpOk
/// # } /// # }

View file

@ -32,6 +32,15 @@ use httpresponse::HttpResponse;
/// max buffer size 64k /// max buffer size 64k
pub(crate) const MAX_WRITE_BUFFER_SIZE: usize = 65_536; pub(crate) const MAX_WRITE_BUFFER_SIZE: usize = 65_536;
/// Create new http server with application factory
pub fn new<F, U, H>(factory: F) -> HttpServer<H>
where F: Fn() -> U + Sync + Send + 'static,
U: IntoIterator<Item=H> + 'static,
H: IntoHttpHandler + 'static
{
HttpServer::new(factory)
}
#[derive(Debug, PartialEq, Clone, Copy)] #[derive(Debug, PartialEq, Clone, Copy)]
/// Server keep-alive setting /// Server keep-alive setting
pub enum KeepAlive { pub enum KeepAlive {