Skip to content
This repository has been archived by the owner on Feb 14, 2023. It is now read-only.

cargo fmt #147

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 9 additions & 10 deletions examples/hyper_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,21 @@ use multipart::client::Multipart;
use std::io::Read;

fn main() {
let url = "http://localhost:80".parse()
.expect("Failed to parse URL");
let url = "http://localhost:80".parse().expect("Failed to parse URL");

let request = Request::new(Method::Post, url)
.expect("Failed to create request");
let request = Request::new(Method::Post, url).expect("Failed to create request");

let mut multipart = Multipart::from_request(request)
.expect("Failed to create Multipart");
let mut multipart = Multipart::from_request(request).expect("Failed to create Multipart");

write_body(&mut multipart)
.expect("Failed to write multipart body");
write_body(&mut multipart).expect("Failed to write multipart body");

let mut response = multipart.send().expect("Failed to send multipart request");

if !response.status.is_success() {
let mut res = String::new();
response.read_to_string(&mut res).expect("failed to read response");
response
.read_to_string(&mut res)
.expect("failed to read response");
println!("response reported unsuccessful: {:?}\n {}", response, res);
}

Expand All @@ -39,6 +37,7 @@ fn write_body(multi: &mut Multipart<Request<Streaming>>) -> hyper::Result<()> {
multi.write_text("text", "Hello, world!")?;
multi.write_file("file", "lorem_ipsum.txt")?;
// &[u8] impl Read
multi.write_stream("binary", &mut binary, None, None)
multi
.write_stream("binary", &mut binary, None, None)
.and(Ok(()))
}
2 changes: 1 addition & 1 deletion examples/hyper_reqbuilder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ fn main() {
// Request is sent here
.client_request(&Client::new(), "http://localhost:80")
.expect("Error sending multipart request");
}
}
22 changes: 11 additions & 11 deletions examples/hyper_server.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
extern crate hyper;
extern crate multipart;

use std::io;
use hyper::server::{Handler, Server, Request, Response};
use hyper::status::StatusCode;
use hyper::server::response::Response as HyperResponse;
use multipart::server::hyper::{Switch, MultipartHandler, HyperRequest};
use multipart::server::{Multipart, Entries, SaveResult};
use hyper::server::{Handler, Request, Response, Server};
use hyper::status::StatusCode;
use multipart::mock::StdoutTee;
use multipart::server::hyper::{HyperRequest, MultipartHandler, Switch};
use multipart::server::{Entries, Multipart, SaveResult};
use std::io;

struct NonMultipart;
impl Handler for NonMultipart {
Expand All @@ -28,7 +28,8 @@ impl MultipartHandler for EchoMultipart {
}
SaveResult::Error(error) => {
println!("Errors saving multipart:\n{:?}", error);
res.send(format!("An error occurred {}", error).as_bytes()).unwrap();
res.send(format!("An error occurred {}", error).as_bytes())
.unwrap();
}
};
}
Expand All @@ -43,9 +44,8 @@ fn process_entries(res: HyperResponse, entries: Entries) -> io::Result<()> {

fn main() {
println!("Listening on 0.0.0.0:3333");
Server::http("0.0.0.0:3333").unwrap().handle(
Switch::new(
NonMultipart,
EchoMultipart
)).unwrap();
Server::http("0.0.0.0:3333")
.unwrap()
.handle(Switch::new(NonMultipart, EchoMultipart))
.unwrap();
}
25 changes: 14 additions & 11 deletions examples/iron.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
extern crate multipart;
extern crate iron;
extern crate multipart;

extern crate env_logger;

use std::io::{self, Write};
use multipart::mock::StdoutTee;
use multipart::server::{Multipart, Entries, SaveResult};
use iron::prelude::*;
use iron::status;
use multipart::mock::StdoutTee;
use multipart::server::{Entries, Multipart, SaveResult};
use std::io::{self, Write};

fn main() {
env_logger::init();

Iron::new(process_request).http("localhost:80").expect("Could not bind localhost:80");
Iron::new(process_request)
.http("localhost:80")
.expect("Could not bind localhost:80");
}

/// Processes a request and returns response or an occured error.
Expand All @@ -29,18 +31,19 @@ fn process_request(request: &mut Request) -> IronResult<Response> {
process_entries(entries.keep_partial())?;
Ok(Response::with((
status::BadRequest,
format!("error reading request: {}", reason.unwrap_err())
format!("error reading request: {}", reason.unwrap_err()),
)))
}
SaveResult::Error(error) => Ok(Response::with((
status::BadRequest,
format!("error reading request: {}", error)
format!("error reading request: {}", error),
))),
}
}
Err(_) => {
Ok(Response::with((status::BadRequest, "The request is not multipart")))
}
Err(_) => Ok(Response::with((
status::BadRequest,
"The request is not multipart",
))),
}
}

Expand All @@ -55,7 +58,7 @@ fn process_entries(entries: Entries) -> IronResult<Response> {
entries.write_debug(tee).map_err(|e| {
IronError::new(
e,
(status::InternalServerError, "Error printing request fields")
(status::InternalServerError, "Error printing request fields"),
)
})?;
}
Expand Down
8 changes: 4 additions & 4 deletions examples/iron_intercept.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,23 @@ extern crate multipart;

use iron::prelude::*;

use multipart::server::Entries;
use multipart::server::iron::Intercept;
use multipart::server::Entries;

fn main() {
// We start with a basic request handler chain.
let mut chain = Chain::new(|req: &mut Request|
let mut chain = Chain::new(|req: &mut Request| {
if let Some(entries) = req.extensions.get::<Entries>() {
Ok(Response::with(format!("{:?}", entries)))
} else {
Ok(Response::with("Not a multipart request"))
}
);
});

// `Intercept` will read out the entries and place them as an extension in the request.
// It has various builder-style methods for changing how it will behave, but has sane settings
// by default.
chain.link_before(Intercept::default());

Iron::new(chain).http("localhost:80").unwrap();
}
}
36 changes: 17 additions & 19 deletions examples/nickel.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,33 @@
extern crate multipart;
extern crate nickel;

use std::io::{self, Write};
use nickel::{Action, HttpRouter, MiddlewareResult, Nickel, Request, Response};
use nickel::status::StatusCode;
use nickel::{Action, HttpRouter, MiddlewareResult, Nickel, Request, Response};
use std::io::{self, Write};

use multipart::mock::StdoutTee;
use multipart::server::nickel::MultipartBody;
use multipart::server::{Entries, SaveResult};
use multipart::mock::StdoutTee;

fn handle_multipart<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> {
match (*req).multipart_body() {
Some(mut multipart) => {
match multipart.save().temp() {
SaveResult::Full(entries) => process_entries(res, entries),

SaveResult::Partial(entries, e) => {
println!("Partial errors ... {:?}", e);
return process_entries(res, entries.keep_partial());
},

SaveResult::Error(e) => {
println!("There are errors in multipart POSTing ... {:?}", e);
res.set(StatusCode::InternalServerError);
return res.send(format!("Server could not handle multipart POST! {:?}", e));
},
Some(mut multipart) => match multipart.save().temp() {
SaveResult::Full(entries) => process_entries(res, entries),

SaveResult::Partial(entries, e) => {
println!("Partial errors ... {:?}", e);
return process_entries(res, entries.keep_partial());
}
}

SaveResult::Error(e) => {
println!("There are errors in multipart POSTing ... {:?}", e);
res.set(StatusCode::InternalServerError);
return res.send(format!("Server could not handle multipart POST! {:?}", e));
}
},
None => {
res.set(StatusCode::BadRequest);
return res.send("Request seems not was a multipart request")
return res.send("Request seems not was a multipart request");
}
}
}
Expand Down
32 changes: 20 additions & 12 deletions examples/rocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,39 +10,45 @@ extern crate multipart;
extern crate rocket;

use multipart::mock::StdoutTee;
use multipart::server::Multipart;
use multipart::server::save::Entries;
use multipart::server::save::SaveResult::*;
use multipart::server::Multipart;

use rocket::Data;
use rocket::http::{ContentType, Status};
use rocket::response::Stream;
use rocket::response::status::Custom;
use rocket::response::Stream;
use rocket::Data;

use std::io::{self, Cursor, Write};

#[post("/upload", data = "<data>")]
// signature requires the request to have a `Content-Type`
fn multipart_upload(cont_type: &ContentType, data: Data) -> Result<Stream<Cursor<Vec<u8>>>, Custom<String>> {
fn multipart_upload(
cont_type: &ContentType,
data: Data,
) -> Result<Stream<Cursor<Vec<u8>>>, Custom<String>> {
// this and the next check can be implemented as a request guard but it seems like just
// more boilerplate than necessary
if !cont_type.is_form_data() {
return Err(Custom(
Status::BadRequest,
"Content-Type not multipart/form-data".into()
"Content-Type not multipart/form-data".into(),
));
}

let (_, boundary) = cont_type.params().find(|&(k, _)| k == "boundary").ok_or_else(
|| Custom(
let (_, boundary) = cont_type
.params()
.find(|&(k, _)| k == "boundary")
.ok_or_else(|| {
Custom(
Status::BadRequest,
"`Content-Type: multipart/form-data` boundary param not provided".into()
"`Content-Type: multipart/form-data` boundary param not provided".into(),
)
)?;
})?;

match process_upload(boundary, data) {
Ok(resp) => Ok(Stream::from(Cursor::new(resp))),
Err(err) => Err(Custom(Status::InternalServerError, err.to_string()))
Err(err) => Err(Custom(Status::InternalServerError, err.to_string())),
}
}

Expand All @@ -61,7 +67,7 @@ fn process_upload(boundary: &str, data: Data) -> io::Result<Vec<u8>> {
}

process_entries(partial.entries, &mut out)?
},
}
Error(e) => return Err(e),
}

Expand All @@ -81,5 +87,7 @@ fn process_entries(entries: Entries, mut out: &mut Vec<u8>) -> io::Result<()> {
}

fn main() {
rocket::ignite().mount("/", routes![multipart_upload]).launch();
rocket::ignite()
.mount("/", routes![multipart_upload])
.launch();
}
25 changes: 15 additions & 10 deletions examples/tiny_http.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
extern crate tiny_http;
extern crate multipart;
extern crate tiny_http;

use std::io::{self, Cursor, Write};
use multipart::server::{Multipart, Entries, SaveResult};
use multipart::mock::StdoutTee;
use tiny_http::{Response, StatusCode, Request};
use multipart::server::{Entries, Multipart, SaveResult};
use std::io::{self, Cursor, Write};
use tiny_http::{Request, Response, StatusCode};
fn main() {
// Starting a server on `localhost:80`
let server = tiny_http::Server::http("localhost:80").expect("Could not bind localhost:80");
Expand All @@ -18,7 +18,10 @@ fn main() {
Ok(resp) => resp,
Err(e) => {
println!("An error has occured during request proccessing: {:?}", e);
build_response(500, "The received data was not correctly proccessed on the server")
build_response(
500,
"The received data was not correctly proccessed on the server",
)
}
};

Expand Down Expand Up @@ -70,9 +73,11 @@ fn process_entries(entries: Entries) -> io::Result<Response<RespBody>> {
fn build_response<D: Into<Vec<u8>>>(status_code: u16, data: D) -> Response<RespBody> {
let data = data.into();
let data_len = data.len();
Response::new(StatusCode(status_code),
vec![],
Cursor::new(data),
Some(data_len),
None)
Response::new(
StatusCode(status_code),
vec![],
Cursor::new(data),
Some(data_len),
None,
)
}
13 changes: 8 additions & 5 deletions src/bin/form_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ use std::fs::File;
use std::io;

fn main() {
let listening = Server::http("127.0.0.1:0").expect("failed to bind socket")
.handle(read_multipart).expect("failed to handle request");
let listening = Server::http("127.0.0.1:0")
.expect("failed to bind socket")
.handle(read_multipart)
.expect("failed to handle request");

println!("bound socket to: {}", listening.socket);
}
Expand All @@ -23,10 +25,11 @@ fn read_multipart(req: Request, mut resp: Response) {
}
}

let mut file = File::open("src/bin/test_form.html")
.expect("failed to open src/bind/test_form.html");
let mut file =
File::open("src/bin/test_form.html").expect("failed to open src/bind/test_form.html");

resp.headers_mut().set(ContentType("text/html".parse().unwrap()));
resp.headers_mut()
.set(ContentType("text/html".parse().unwrap()));

let mut resp = resp.start().expect("failed to open response");
io::copy(&mut file, &mut resp).expect("failed to write response");
Expand Down
Loading