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

Fix typos #145

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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Provides server-side integration with `tiny_http::Request` via `multipart::serve
### [Rocket ![](https://img.shields.io/crates/v/rocket.svg)](https://crates.io/crates/rocket)

Direct integration is not provided as the Rocket folks seem to want to handle `multipart/form-data`
behind the scenes which would supercede any integration with `multipart`. However, an example is available
behind the scenes which would supersede any integration with `multipart`. However, an example is available
showing how to use `multipart` on a Rocket server: [examples/rocket.rs](examples/rocket.rs)

## ⚡ Powered By ⚡
Expand Down
2 changes: 1 addition & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ Author: [abonander]

This example shows how `multipart`'s server API can be used with [Rocket](https://rocket.rs) without
explicit support (the Rocket folks seem to want to handle `multipart/form-data` behind the scenes
but haven't gotten around to implementing it yet; this would supercede any integration from `multipart`).
but haven't gotten around to implementing it yet; this would supersede any integration from `multipart`).

```
$ cargo run --example rocket --features "rocket"
Expand Down
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();
}
27 changes: 15 additions & 12 deletions examples/iron.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
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.
/// Processes a request and returns response or an occurred error.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo is fixed here.

fn process_request(request: &mut Request) -> IronResult<Response> {
// Getting a multipart reader wrapper
match Multipart::from_request(request) {
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();
}
31 changes: 18 additions & 13 deletions examples/tiny_http.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
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");
loop {
// This blocks until the next request is received
let mut request = server.recv().unwrap();

// Processes a request and returns response or an occured error
// Processes a request and returns response or an occurred error
let result = process_request(&mut request);
let resp = match result {
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")
println!("An error has occurred during request processing: {:?}", e);
build_response(
500,
"The received data was not correctly processed on the server",
)
}
};

Expand All @@ -29,7 +32,7 @@ fn main() {

type RespBody = Cursor<Vec<u8>>;

/// Processes a request and returns response or an occured error.
/// Processes a request and returns response or an occurred error.
fn process_request(request: &mut Request) -> io::Result<Response<RespBody>> {
// Getting a multipart reader wrapper
match Multipart::from_request(request) {
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,
)
}
Loading