mirror of
https://github.com/fafhrd91/actix-web
synced 2024-11-27 17:52:56 +01:00
update examples
This commit is contained in:
parent
9e751de707
commit
8d8f6bedad
@ -8,8 +8,10 @@ extern crate futures;
|
||||
use futures::Stream;
|
||||
|
||||
use std::{io, env};
|
||||
use actix_web::*;
|
||||
use actix_web::middleware::RequestSession;
|
||||
use actix_web::{error, fs, pred,
|
||||
Application, HttpRequest, HttpResponse, HttpServer, Result, Error};
|
||||
use actix_web::http::{Method, StatusCode};
|
||||
use actix_web::middleware::{self, RequestSession};
|
||||
use futures::future::{FutureResult, result};
|
||||
|
||||
/// favicon handler
|
||||
@ -118,9 +120,9 @@ fn main() {
|
||||
.resource("/async/{name}", |r| r.method(Method::GET).a(index_async))
|
||||
.resource("/test", |r| r.f(|req| {
|
||||
match *req.method() {
|
||||
Method::GET => httpcodes::HTTPOk,
|
||||
Method::POST => httpcodes::HTTPMethodNotAllowed,
|
||||
_ => httpcodes::HTTPNotFound,
|
||||
Method::GET => HttpResponse::Ok(),
|
||||
Method::POST => HttpResponse::MethodNotAllowed(),
|
||||
_ => HttpResponse::NotFound(),
|
||||
}
|
||||
}))
|
||||
.resource("/error.html", |r| r.f(|req| {
|
||||
@ -140,7 +142,8 @@ fn main() {
|
||||
// default
|
||||
.default_resource(|r| {
|
||||
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")
|
||||
|
@ -16,8 +16,9 @@ extern crate actix;
|
||||
extern crate actix_web;
|
||||
extern crate env_logger;
|
||||
|
||||
use actix::*;
|
||||
use actix_web::*;
|
||||
use actix::prelude::*;
|
||||
use actix_web::{http, middleware,
|
||||
Application, HttpServer, HttpRequest, HttpResponse, Error, AsyncResponder};
|
||||
|
||||
use diesel::prelude::*;
|
||||
use futures::future::Future;
|
||||
@ -43,8 +44,8 @@ fn index(req: HttpRequest<State>) -> Box<Future<Item=HttpResponse, Error=Error>>
|
||||
.from_err()
|
||||
.and_then(|res| {
|
||||
match res {
|
||||
Ok(user) => Ok(httpcodes::HTTPOk.build().json(user)?),
|
||||
Err(_) => Ok(httpcodes::HTTPInternalServerError.into())
|
||||
Ok(user) => Ok(HttpResponse::Ok().json(user)?),
|
||||
Err(_) => Ok(HttpResponse::InternalServerError().into())
|
||||
}
|
||||
})
|
||||
.responder()
|
||||
@ -65,7 +66,7 @@ fn main() {
|
||||
Application::with_state(State{db: addr.clone()})
|
||||
// enable logger
|
||||
.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()
|
||||
.start();
|
||||
|
||||
|
@ -2,7 +2,7 @@ extern crate actix;
|
||||
extern crate actix_web;
|
||||
extern crate env_logger;
|
||||
|
||||
use actix_web::*;
|
||||
use actix_web::{Application, HttpRequest, server, middleware};
|
||||
|
||||
|
||||
fn index(_req: HttpRequest) -> &'static str {
|
||||
@ -14,7 +14,7 @@ fn main() {
|
||||
let _ = env_logger::init();
|
||||
let sys = actix::System::new("ws-example");
|
||||
|
||||
let _addr = HttpServer::new(
|
||||
let _addr = server::new(
|
||||
|| Application::new()
|
||||
// enable logger
|
||||
.middleware(middleware::Logger::default())
|
||||
|
@ -3,23 +3,24 @@ extern crate actix_web;
|
||||
extern crate futures;
|
||||
extern crate env_logger;
|
||||
|
||||
use actix_web::*;
|
||||
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
|
||||
fn index(_req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
||||
client::ClientRequest::get("https://www.rust-lang.org/en-US/")
|
||||
.finish().unwrap()
|
||||
.send()
|
||||
.map_err(error::Error::from) // <- convert SendRequestError to an Error
|
||||
.map_err(Error::from) // <- convert SendRequestError to an Error
|
||||
.and_then(
|
||||
|resp| resp.body() // <- this is MessageBody type, resolves to complete body
|
||||
.from_err() // <- convert PayloadError to a Error
|
||||
.and_then(|body| { // <- we got complete body, now send as server response
|
||||
httpcodes::HttpOk.build()
|
||||
HttpResponse::Ok()
|
||||
.body(body)
|
||||
.map_err(error::Error::from)
|
||||
.map_err(Error::from)
|
||||
}))
|
||||
.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/")
|
||||
.finish().unwrap()
|
||||
.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
|
||||
httpcodes::HttpOk.build()
|
||||
HttpResponse::Ok()
|
||||
// read one chunk from client response and send this chunk to a server response
|
||||
// .from_err() converts PayloadError to a Error
|
||||
.body(Body::Streaming(Box::new(resp.from_err())))
|
||||
@ -46,7 +47,7 @@ fn main() {
|
||||
env_logger::init();
|
||||
let sys = actix::System::new("http-proxy");
|
||||
|
||||
let _addr = HttpServer::new(
|
||||
let _addr = server::new(
|
||||
|| Application::new()
|
||||
.middleware(middleware::Logger::default())
|
||||
.resource("/streaming", |r| r.f(streaming))
|
||||
|
@ -7,7 +7,9 @@ extern crate serde_json;
|
||||
#[macro_use] extern crate serde_derive;
|
||||
#[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 futures::{Future, Stream};
|
||||
@ -25,15 +27,15 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
||||
.from_err() // convert all errors into `Error`
|
||||
.and_then(|val: MyObj| {
|
||||
println!("model: {:?}", val);
|
||||
Ok(httpcodes::HTTPOk.build().json(val)?) // <- send response
|
||||
Ok(HttpResponse::Ok().json(val)?) // <- send response
|
||||
})
|
||||
.responder()
|
||||
}
|
||||
|
||||
/// 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);
|
||||
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
|
||||
@ -62,7 +64,7 @@ fn index_manual(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>>
|
||||
.and_then(|body| {
|
||||
// body is loaded, now we can deserialize serde-json
|
||||
let obj = serde_json::from_slice::<MyObj>(&body)?;
|
||||
Ok(httpcodes::HTTPOk.build().json(obj)?) // <- send response
|
||||
Ok(HttpResponse::Ok().json(obj)?) // <- send response
|
||||
})
|
||||
.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
|
||||
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() } };
|
||||
Ok(HttpResponse::build(StatusCode::OK)
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(injson.dump()).unwrap())
|
||||
})
|
||||
@ -87,15 +89,15 @@ fn main() {
|
||||
let _ = env_logger::init();
|
||||
let sys = actix::System::new("json-example");
|
||||
|
||||
let addr = HttpServer::new(|| {
|
||||
let _ = server::new(|| {
|
||||
Application::new()
|
||||
// enable logger
|
||||
.middleware(middleware::Logger::default())
|
||||
.resource("/extractor/{name}/{number}/",
|
||||
|r| r.method(Method::GET).with(extract_item))
|
||||
.resource("/manual", |r| r.method(Method::POST).f(index_manual))
|
||||
.resource("/mjsonrust", |r| r.method(Method::POST).f(index_mjsonrust))
|
||||
.resource("/", |r| r.method(Method::POST).f(index))})
|
||||
|r| r.method(http::Method::GET).with(extract_item))
|
||||
.resource("/manual", |r| r.method(http::Method::POST).f(index_manual))
|
||||
.resource("/mjsonrust", |r| r.method(http::Method::POST).f(index_mjsonrust))
|
||||
.resource("/", |r| r.method(http::Method::POST).f(index))})
|
||||
.bind("127.0.0.1:8080").unwrap()
|
||||
.shutdown_timeout(1)
|
||||
.start();
|
||||
|
@ -12,8 +12,10 @@ extern crate actix;
|
||||
extern crate actix_web;
|
||||
extern crate env_logger;
|
||||
|
||||
use actix::*;
|
||||
use actix_web::*;
|
||||
use actix::prelude::*;
|
||||
use actix_web::{middleware, http, server,
|
||||
Application, AsyncResponder,
|
||||
HttpRequest, HttpResponse, HttpMessage, Error};
|
||||
use juniper::http::graphiql::graphiql_source;
|
||||
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");
|
||||
Ok(HttpResponse::build(StatusCode::OK)
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("text/html; charset=utf-8")
|
||||
.body(html).unwrap())
|
||||
}
|
||||
@ -77,8 +79,8 @@ fn graphql(req: HttpRequest<State>) -> Box<Future<Item=HttpResponse, Error=Error
|
||||
.from_err()
|
||||
.and_then(|res| {
|
||||
match res {
|
||||
Ok(user) => Ok(httpcodes::HTTPOk.build().body(user)?),
|
||||
Err(_) => Ok(httpcodes::HTTPInternalServerError.into())
|
||||
Ok(user) => Ok(HttpResponse::Ok().body(user)?),
|
||||
Err(_) => Ok(HttpResponse::InternalServerError().into())
|
||||
}
|
||||
})
|
||||
})
|
||||
@ -96,12 +98,12 @@ fn main() {
|
||||
});
|
||||
|
||||
// Start http server
|
||||
let _addr = HttpServer::new(move || {
|
||||
let _ = server::new(move || {
|
||||
Application::with_state(State{executor: addr.clone()})
|
||||
// enable logger
|
||||
.middleware(middleware::Logger::default())
|
||||
.resource("/graphql", |r| r.method(Method::POST).a(graphql))
|
||||
.resource("/graphiql", |r| r.method(Method::GET).f(graphiql))})
|
||||
.resource("/graphql", |r| r.method(http::Method::POST).h(graphql))
|
||||
.resource("/graphiql", |r| r.method(http::Method::GET).h(graphiql))})
|
||||
.bind("127.0.0.1:8080").unwrap()
|
||||
.start();
|
||||
|
||||
|
@ -5,7 +5,9 @@ extern crate env_logger;
|
||||
extern crate futures;
|
||||
|
||||
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::{result, Either};
|
||||
@ -38,7 +40,7 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>>
|
||||
}
|
||||
})
|
||||
.finish() // <- Stream::finish() combinator from actix
|
||||
.map(|_| httpcodes::HTTPOk.into())
|
||||
.map(|_| HttpResponse::Ok().into())
|
||||
.responder()
|
||||
}
|
||||
|
||||
@ -47,10 +49,10 @@ fn main() {
|
||||
let _ = env_logger::init();
|
||||
let sys = actix::System::new("multipart-example");
|
||||
|
||||
let addr = HttpServer::new(
|
||||
let _ = server::new(
|
||||
|| Application::new()
|
||||
.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()
|
||||
.start();
|
||||
|
||||
|
@ -9,8 +9,10 @@ extern crate prost;
|
||||
#[macro_use]
|
||||
extern crate prost_derive;
|
||||
|
||||
use actix_web::*;
|
||||
use futures::Future;
|
||||
use actix_web::{
|
||||
http, middleware, server,
|
||||
Application, AsyncResponder, HttpRequest, HttpResponse, Error};
|
||||
|
||||
mod protobuf;
|
||||
use protobuf::ProtoBufResponseBuilder;
|
||||
@ -31,7 +33,7 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
||||
.from_err() // convert all errors into `Error`
|
||||
.and_then(|val: MyObj| {
|
||||
println!("model: {:?}", val);
|
||||
Ok(httpcodes::HTTPOk.build().protobuf(val)?) // <- send response
|
||||
Ok(HttpResponse::Ok().protobuf(val)?) // <- send response
|
||||
})
|
||||
.responder()
|
||||
}
|
||||
@ -39,13 +41,13 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
||||
|
||||
fn main() {
|
||||
::std::env::set_var("RUST_LOG", "actix_web=info");
|
||||
let _ = env_logger::init();
|
||||
env_logger::init();
|
||||
let sys = actix::System::new("protobuf-example");
|
||||
|
||||
let addr = HttpServer::new(|| {
|
||||
let _ = server::new(|| {
|
||||
Application::new()
|
||||
.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()
|
||||
.shutdown_timeout(1)
|
||||
.start();
|
||||
|
@ -6,7 +6,7 @@ use prost::Message;
|
||||
use prost::DecodeError as ProtoBufDecodeError;
|
||||
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::dev::HttpResponseBuilder;
|
||||
use actix_web::error::{Error, PayloadError, ResponseError};
|
||||
|
@ -10,8 +10,10 @@ extern crate r2d2;
|
||||
extern crate r2d2_sqlite;
|
||||
extern crate rusqlite;
|
||||
|
||||
use actix::*;
|
||||
use actix_web::*;
|
||||
use actix::prelude::*;
|
||||
use actix_web::{
|
||||
middleware, http, server,
|
||||
Application, AsyncResponder, HttpRequest, HttpResponse, Error};
|
||||
use futures::future::Future;
|
||||
use r2d2_sqlite::SqliteConnectionManager;
|
||||
|
||||
@ -32,8 +34,8 @@ fn index(req: HttpRequest<State>) -> Box<Future<Item=HttpResponse, Error=Error>>
|
||||
.from_err()
|
||||
.and_then(|res| {
|
||||
match res {
|
||||
Ok(user) => Ok(httpcodes::HTTPOk.build().json(user)?),
|
||||
Err(_) => Ok(httpcodes::HTTPInternalServerError.into())
|
||||
Ok(user) => Ok(HttpResponse::Ok().json(user)?),
|
||||
Err(_) => Ok(HttpResponse::InternalServerError().into())
|
||||
}
|
||||
})
|
||||
.responder()
|
||||
@ -41,7 +43,7 @@ fn index(req: HttpRequest<State>) -> Box<Future<Item=HttpResponse, Error=Error>>
|
||||
|
||||
fn main() {
|
||||
::std::env::set_var("RUST_LOG", "actix_web=debug");
|
||||
let _ = env_logger::init();
|
||||
env_logger::init();
|
||||
let sys = actix::System::new("r2d2-example");
|
||||
|
||||
// r2d2 pool
|
||||
@ -52,11 +54,11 @@ fn main() {
|
||||
let addr = SyncArbiter::start(3, move || DbExecutor(pool.clone()));
|
||||
|
||||
// Start http server
|
||||
let _addr = HttpServer::new(move || {
|
||||
let _ = server::new(move || {
|
||||
Application::with_state(State{db: addr.clone()})
|
||||
// enable logger
|
||||
.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()
|
||||
.start();
|
||||
|
||||
|
@ -9,8 +9,10 @@ extern crate env_logger;
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use actix::*;
|
||||
use actix_web::*;
|
||||
use actix::prelude::*;
|
||||
use actix_web::{
|
||||
http, server, ws, middleware,
|
||||
Application, HttpRequest, HttpResponse, Error};
|
||||
|
||||
/// Application state
|
||||
struct AppState {
|
||||
@ -18,12 +20,11 @@ struct AppState {
|
||||
}
|
||||
|
||||
/// simple handle
|
||||
fn index(req: HttpRequest<AppState>) -> HttpResponse {
|
||||
fn index(req: HttpRequest<AppState>) -> Result<HttpResponse, Error> {
|
||||
println!("{:?}", req);
|
||||
req.state().counter.set(req.state().counter.get() + 1);
|
||||
|
||||
httpcodes::HTTPOk.with_body(
|
||||
format!("Num of requests: {}", req.state().counter.get()))
|
||||
HttpResponse::Ok().body(format!("Num of requests: {}", req.state().counter.get()))
|
||||
}
|
||||
|
||||
/// `MyWebSocket` counts how many messages it receives from peer,
|
||||
@ -58,14 +59,15 @@ fn main() {
|
||||
let _ = env_logger::init();
|
||||
let sys = actix::System::new("ws-example");
|
||||
|
||||
let addr = HttpServer::new(
|
||||
let _ = server::new(
|
||||
|| Application::with_state(AppState{counter: Cell::new(0)})
|
||||
// enable logger
|
||||
.middleware(middleware::Logger::default())
|
||||
// websocket route
|
||||
.resource(
|
||||
"/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
|
||||
.resource("/", |r| r.f(index)))
|
||||
.bind("127.0.0.1:8080").unwrap()
|
||||
|
@ -4,14 +4,17 @@ extern crate env_logger;
|
||||
#[macro_use]
|
||||
extern crate tera;
|
||||
|
||||
use actix_web::*;
|
||||
use actix_web::{
|
||||
http, error, middleware, server,
|
||||
Application, HttpRequest, HttpResponse, Error,
|
||||
};
|
||||
|
||||
|
||||
struct 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 mut ctx = tera::Context::new();
|
||||
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())
|
||||
.map_err(|_| error::ErrorInternalServerError("Template error"))?
|
||||
};
|
||||
Ok(httpcodes::HTTPOk.build()
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("text/html")
|
||||
.body(s)?)
|
||||
}
|
||||
@ -32,13 +35,13 @@ fn main() {
|
||||
let _ = env_logger::init();
|
||||
let sys = actix::System::new("tera-example");
|
||||
|
||||
let addr = HttpServer::new(|| {
|
||||
let _ = server::new(|| {
|
||||
let tera = compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"));
|
||||
|
||||
Application::with_state(State{template: tera})
|
||||
// enable logger
|
||||
.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()
|
||||
.start();
|
||||
|
||||
|
@ -4,15 +4,16 @@ extern crate actix_web;
|
||||
extern crate env_logger;
|
||||
extern crate openssl;
|
||||
|
||||
use actix_web::*;
|
||||
use openssl::ssl::{SslMethod, SslAcceptor, SslFiletype};
|
||||
use actix_web::{
|
||||
http, middleware, server,
|
||||
Application, HttpRequest, HttpResponse, Error};
|
||||
|
||||
|
||||
/// simple handle
|
||||
fn index(req: HttpRequest) -> Result<HttpResponse> {
|
||||
fn index(req: HttpRequest) -> Result<HttpResponse, Error> {
|
||||
println!("{:?}", req);
|
||||
Ok(httpcodes::HTTPOk
|
||||
.build()
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("text/plain")
|
||||
.body("Welcome!")?)
|
||||
}
|
||||
@ -21,7 +22,7 @@ fn main() {
|
||||
if ::std::env::var("RUST_LOG").is_err() {
|
||||
::std::env::set_var("RUST_LOG", "actix_web=info");
|
||||
}
|
||||
let _ = env_logger::init();
|
||||
env_logger::init();
|
||||
let sys = actix::System::new("ws-example");
|
||||
|
||||
// load ssl keys
|
||||
@ -29,18 +30,17 @@ fn main() {
|
||||
builder.set_private_key_file("key.pem", SslFiletype::PEM).unwrap();
|
||||
builder.set_certificate_chain_file("cert.pem").unwrap();
|
||||
|
||||
let addr = HttpServer::new(
|
||||
let _ = server::new(
|
||||
|| Application::new()
|
||||
// enable logger
|
||||
.middleware(middleware::Logger::default())
|
||||
// register simple handler, handle all methods
|
||||
.resource("/index.html", |r| r.f(index))
|
||||
// with path parameters
|
||||
.resource("/", |r| r.method(Method::GET).f(|req| {
|
||||
httpcodes::HTTPFound
|
||||
.build()
|
||||
.resource("/", |r| r.method(http::Method::GET).f(|req| {
|
||||
HttpResponse::Found()
|
||||
.header("LOCATION", "/index.html")
|
||||
.body(Body::Empty)
|
||||
.finish()
|
||||
})))
|
||||
.bind("127.0.0.1:8443").unwrap()
|
||||
.start_ssl(builder).unwrap();
|
||||
|
@ -5,12 +5,11 @@ extern crate futures;
|
||||
extern crate actix;
|
||||
extern crate actix_web;
|
||||
extern crate env_logger;
|
||||
extern crate http;
|
||||
|
||||
use std::env;
|
||||
use http::header;
|
||||
use actix_web::*;
|
||||
use actix_web::middleware::cors;
|
||||
use actix_web::{
|
||||
http, middleware, server,
|
||||
Application};
|
||||
|
||||
mod user;
|
||||
use user::info;
|
||||
@ -22,20 +21,21 @@ fn main() {
|
||||
|
||||
let sys = actix::System::new("Actix-web-CORS");
|
||||
|
||||
HttpServer::new(
|
||||
server::new(
|
||||
|| Application::new()
|
||||
.middleware(middleware::Logger::default())
|
||||
.resource("/user/info", |r| {
|
||||
cors::Cors::build()
|
||||
.allowed_origin("http://localhost:1234")
|
||||
.allowed_methods(vec!["GET", "POST"])
|
||||
middleware::cors::Cors::build()
|
||||
.allowed_origin("http://localhost:1234")
|
||||
.allowed_methods(vec!["GET", "POST"])
|
||||
.allowed_headers(
|
||||
vec![header::AUTHORIZATION,
|
||||
header::ACCEPT, header::CONTENT_TYPE])
|
||||
vec![http::header::AUTHORIZATION,
|
||||
http::header::ACCEPT,
|
||||
http::header::CONTENT_TYPE])
|
||||
.max_age(3600)
|
||||
.finish().expect("Can not create CORS middleware")
|
||||
.register(r);
|
||||
r.method(Method::POST).a(info);
|
||||
r.method(http::Method::POST).a(info);
|
||||
}))
|
||||
.bind("127.0.0.1:8000").unwrap()
|
||||
.shutdown_timeout(200)
|
||||
|
@ -14,6 +14,6 @@ pub fn info(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
||||
req.json()
|
||||
.from_err()
|
||||
.and_then(|res: Info| {
|
||||
Ok(httpcodes::HTTPOk.build().json(res)?)
|
||||
Ok(httpcodes::HttpOk.build().json(res)?)
|
||||
}).responder()
|
||||
}
|
||||
|
@ -17,7 +17,9 @@ extern crate actix_web;
|
||||
use std::time::Instant;
|
||||
|
||||
use actix::*;
|
||||
use actix_web::*;
|
||||
use actix_web::{
|
||||
http, fs, ws,
|
||||
Application, HttpRequest, HttpResponse, HttpServer, Error};
|
||||
|
||||
mod codec;
|
||||
mod server;
|
||||
@ -30,7 +32,7 @@ struct WsChatSessionState {
|
||||
}
|
||||
|
||||
/// Entry point for our route
|
||||
fn chat_route(req: HttpRequest<WsChatSessionState>) -> Result<HttpResponse> {
|
||||
fn chat_route(req: HttpRequest<WsChatSessionState>) -> Result<HttpResponse, Error> {
|
||||
ws::start(
|
||||
req,
|
||||
WsChatSession {
|
||||
@ -190,9 +192,8 @@ fn main() {
|
||||
|
||||
Application::with_state(state)
|
||||
// redirect to websocket.html
|
||||
.resource("/", |r| r.method(Method::GET).f(|_| {
|
||||
httpcodes::HTTPFound
|
||||
.build()
|
||||
.resource("/", |r| r.method(http::Method::GET).f(|_| {
|
||||
HttpResponse::Found()
|
||||
.header("LOCATION", "/static/websocket.html")
|
||||
.finish()
|
||||
}))
|
||||
|
@ -8,11 +8,14 @@ extern crate actix;
|
||||
extern crate actix_web;
|
||||
extern crate env_logger;
|
||||
|
||||
use actix::*;
|
||||
use actix_web::*;
|
||||
use actix::prelude::*;
|
||||
use actix_web::{
|
||||
http, middleware, server, fs, ws,
|
||||
Application, HttpRequest, HttpResponse, Error,
|
||||
};
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
@ -47,12 +50,12 @@ fn main() {
|
||||
let _ = env_logger::init();
|
||||
let sys = actix::System::new("ws-example");
|
||||
|
||||
let _addr = HttpServer::new(
|
||||
server::new(
|
||||
|| Application::new()
|
||||
// enable logger
|
||||
.middleware(middleware::Logger::default())
|
||||
// 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
|
||||
.handler("/", fs::StaticFiles::new("../static/", true)
|
||||
.index_file("index.html")))
|
||||
|
@ -35,7 +35,7 @@ use httpresponse::HttpResponse;
|
||||
/// # #[macro_use] extern crate serde_derive;
|
||||
/// # use actix_web::*;
|
||||
/// use actix_web::http::NormalizePath;
|
||||
/// #
|
||||
///
|
||||
/// # fn index(req: HttpRequest) -> httpcodes::StaticResponse {
|
||||
/// # httpcodes::HttpOk
|
||||
/// # }
|
||||
|
@ -32,6 +32,15 @@ use httpresponse::HttpResponse;
|
||||
/// max buffer size 64k
|
||||
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)]
|
||||
/// Server keep-alive setting
|
||||
pub enum KeepAlive {
|
||||
|
Loading…
Reference in New Issue
Block a user