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

actix examples in actix release version

This commit is contained in:
krircc
2018-04-13 09:18:42 +08:00
parent ad58e559a0
commit 3ebde8e7c2
88 changed files with 3829 additions and 2 deletions

14
multipart/Cargo.toml Normal file
View File

@ -0,0 +1,14 @@
[package]
name = "multipart-example"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
[[bin]]
name = "multipart"
path = "src/main.rs"
[dependencies]
env_logger = "*"
futures = "0.1"
actix = "0.5"
actix-web = "^0.5"

24
multipart/README.md Normal file
View File

@ -0,0 +1,24 @@
# multipart
Multipart's `Getting Started` guide for Actix web
## Usage
### server
```bash
cd actix-web/examples/multipart
cargo run (or ``cargo watch -x run``)
# Started http server: 127.0.0.1:8080
```
### client
- ``pip install aiohttp``
- ``python client.py``
- you must see in server console multipart fields
if ubuntu :
- ``pip3 install aiohttp``
- ``python3 client.py``

34
multipart/client.py Normal file
View File

@ -0,0 +1,34 @@
# This script could be used for actix-web multipart example test
# just start server and run client.py
import asyncio
import aiohttp
async def req1():
with aiohttp.MultipartWriter() as writer:
writer.append('test')
writer.append_json({'passed': True})
resp = await aiohttp.ClientSession().request(
"post", 'http://localhost:8080/multipart',
data=writer, headers=writer.headers)
print(resp)
assert 200 == resp.status
async def req2():
with aiohttp.MultipartWriter() as writer:
writer.append('test')
writer.append_json({'passed': True})
writer.append(open('src/main.rs'))
resp = await aiohttp.ClientSession().request(
"post", 'http://localhost:8080/multipart',
data=writer, headers=writer.headers)
print(resp)
assert 200 == resp.status
loop = asyncio.get_event_loop()
loop.run_until_complete(req1())
loop.run_until_complete(req2())

61
multipart/src/main.rs Normal file
View File

@ -0,0 +1,61 @@
#![allow(unused_variables)]
extern crate actix;
extern crate actix_web;
extern crate env_logger;
extern crate futures;
use actix::*;
use actix_web::{
http, middleware, multipart, server,
App, AsyncResponder, HttpRequest, HttpResponse, HttpMessage, Error};
use futures::{Future, Stream};
use futures::future::{result, Either};
fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>>
{
println!("{:?}", req);
req.multipart() // <- get multipart stream for current request
.from_err() // <- convert multipart errors
.and_then(|item| { // <- iterate over multipart items
match item {
// Handle multipart Field
multipart::MultipartItem::Field(field) => {
println!("==== FIELD ==== {:?}", field);
// Field in turn is stream of *Bytes* object
Either::A(
field.map_err(Error::from)
.map(|chunk| {
println!("-- CHUNK: \n{}",
std::str::from_utf8(&chunk).unwrap());})
.finish())
},
multipart::MultipartItem::Nested(mp) => {
// Or item could be nested Multipart stream
Either::B(result(Ok(())))
}
}
})
.finish() // <- Stream::finish() combinator from actix
.map(|_| HttpResponse::Ok().into())
.responder()
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
let _ = env_logger::init();
let sys = actix::System::new("multipart-example");
server::new(
|| App::new()
.middleware(middleware::Logger::default()) // <- logger
.resource("/multipart", |r| r.method(http::Method::POST).a(index)))
.bind("127.0.0.1:8080").unwrap()
.start();
println!("Starting http server: 127.0.0.1:8080");
let _ = sys.run();
}