1
0
mirror of https://github.com/actix/actix-extras.git synced 2025-08-31 11:26:59 +02:00

add actix-web-cors example

This commit is contained in:
krircc
2018-01-27 11:00:26 +08:00
parent 550f68ca05
commit 74166b4834
12 changed files with 511 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
/target/
**/*.rs.bk
Cargo.lock

View File

@@ -0,0 +1,17 @@
[package]
name = "Actix-web-CORS"
version = "0.1.0"
authors = ["krircc <krircc@aliyun.com>"]
[dependencies]
serde = "^1.0.0"
serde_derive = "^1.0.0"
serde_json = "^1.0.0"
http = "^0.1.0"
num_cpus = "1.0"
actix = "^0.4.0"
actix-web = { git = "https://github.com/actix/actix-web" }
dotenv = "^0.10.0"
env_logger = "^0.5.0"
futures = "0.1"

View File

@@ -0,0 +1,47 @@
#![allow(warnings)]
#[macro_use] extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate futures;
extern crate num_cpus;
extern crate actix;
extern crate actix_web;
extern crate env_logger;
extern crate http;
use actix::*;
use actix_web::*;
use std::env;
mod user;
use http::header;
use actix_web::middleware::cors;
use user:: info;
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
let _ = env_logger::init();
let sys = actix::System::new("Actix-web-CORS");
env::set_var("RUST_BACKTRACE", "1");
HttpServer::new(
|| Application::new()
.middleware(middleware::Logger::default())
.resource("/user/info", |r| {
cors::Cors::build()
.allowed_origin("http://localhost:1234")
.allowed_methods(vec!["GET", "POST"])
.allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
.allowed_header(header::CONTENT_TYPE)
.max_age(3600)
.finish().expect("Can not create CORS middleware")
.register(r);
r.method(Method::POST).a(info);
}))
.bind("127.0.0.1:8000").unwrap()
.shutdown_timeout(200)
.start();
let _ = sys.run();
}

View File

@@ -0,0 +1,19 @@
use actix::*;
use actix_web::*;
use futures::future::Future;
#[derive(Deserialize,Serialize, Debug)]
struct Info {
username: String,
email: String,
password: String,
confirm_password: String,
}
pub fn info(mut req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
req.json()
.from_err()
.and_then(|res: Info| {
Ok(httpcodes::HTTPOk.build().json(res)?)
}).responder()
}