Rocket/examples/manual_routes/src/main.rs

89 lines
2.6 KiB
Rust
Raw Normal View History

extern crate rocket;
2017-01-09 02:02:12 +00:00
#[cfg(test)]
mod tests;
use std::io;
use std::fs::File;
use rocket::{Request, Route, Data, Catcher, Error};
use rocket::http::{Status, RawStr};
use rocket::response::{self, Responder};
2017-01-09 02:02:12 +00:00
use rocket::response::status::Custom;
use rocket::handler::Outcome;
use rocket::http::Method::*;
fn forward(_req: &Request, data: Data) -> Outcome<'static> {
Outcome::forward(data)
}
fn hi(req: &Request, _: Data) -> Outcome<'static> {
Outcome::from(req, "Hello!")
}
fn name<'a>(req: &'a Request, _: Data) -> Outcome<'a> {
let param = req.get_param::<&'a RawStr>(0);
Outcome::from(req, param.map(|r| r.as_str()).unwrap_or("unnamed"))
}
fn echo_url(req: &Request, _: Data) -> Outcome<'static> {
2017-01-09 02:02:12 +00:00
let param = req.uri()
Overhaul URI types. This is fairly large commit with several entangled logical changes. The primary change in this commit is to completely overhaul how URI handling in Rocket works. Prior to this commit, the `Uri` type acted as an origin API. Its parser was minimal and lenient, allowing URIs that were invalid according to RFC 7230. By contrast, the new `Uri` type brings with it a strict RFC 7230 compliant parser. The `Uri` type now represents any kind of valid URI, not simply `Origin` types. Three new URI types were introduced: * `Origin` - represents valid origin URIs * `Absolute` - represents valid absolute URIs * `Authority` - represents valid authority URIs The `Origin` type replaces `Uri` in many cases: * As fields and method inputs of `Route` * The `&Uri` request guard is now `&Origin` * The `uri!` macro produces an `Origin` instead of a `Uri` The strict nature of URI parsing cascaded into the following changes: * Several `Route` methods now `panic!` on invalid URIs * The `Rocket::mount()` method is (correctly) stricter with URIs * The `Redirect` constructors take a `TryInto<Uri>` type * Dispatching of a `LocalRequest` correctly validates URIs Overall, URIs are now properly and uniformly handled throughout Rocket's codebase, resulting in a more reliable and correct system. In addition to these URI changes, the following changes are also part of this commit: * The `LocalRequest::cloned_dispatch()` method was removed in favor of chaining `.clone().dispatch()`. * The entire Rocket codebase uses `crate` instead of `pub(crate)` as a visibility modifier. * Rocket uses the `crate_visibility_modifier` and `try_from` features. A note on unsafety: this commit introduces many uses of `unsafe` in the URI parser. All of these uses are a result of unsafely transforming byte slices (`&[u8]` or similar) into strings (`&str`). The parser ensures that these casts are safe, but of course, we must label their use `unsafe`. The parser was written to be as generic and efficient as possible and thus can parse directly from byte sources. Rocket, however, does not make use of this fact and so would be able to remove all uses of `unsafe` by parsing from an existing `&str`. This should be considered in the future. Fixes #443. Resolves #263.
2018-07-29 01:26:15 +00:00
.path()
2017-01-09 02:02:12 +00:00
.split_at(6)
.1;
Outcome::from(req, RawStr::from_str(param).url_decode())
}
fn upload<'r>(req: &'r Request, data: Data) -> Outcome<'r> {
if !req.content_type().map_or(false, |ct| ct.is_plain()) {
println!(" => Content-Type of upload must be text/plain. Ignoring.");
return Outcome::failure(Status::BadRequest);
}
2016-10-09 11:29:02 +00:00
let file = File::create("/tmp/upload.txt");
if let Ok(mut file) = file {
2016-10-09 11:29:02 +00:00
if let Ok(n) = io::copy(&mut data.open(), &mut file) {
return Outcome::from(req, format!("OK: {} bytes uploaded.", n));
}
println!(" => Failed copying.");
Outcome::failure(Status::InternalServerError)
} else {
println!(" => Couldn't open file: {:?}", file.unwrap_err());
Outcome::failure(Status::InternalServerError)
}
}
fn get_upload(req: &Request, _: Data) -> Outcome<'static> {
Outcome::from(req, File::open("/tmp/upload.txt").ok())
}
fn not_found_handler<'r>(_: Error, req: &'r Request) -> response::Result<'r> {
let res = Custom(Status::NotFound, format!("Couldn't find: {}", req.uri()));
res.respond_to(req)
}
2017-01-09 02:02:12 +00:00
fn rocket() -> rocket::Rocket {
let always_forward = Route::ranked(1, Get, "/", forward);
let hello = Route::ranked(2, Get, "/", hi);
let echo = Route::new(Get, "/echo:<str>", echo_url);
let name = Route::new(Get, "/<name>", name);
let post_upload = Route::new(Post, "/", upload);
let get_upload = Route::new(Get, "/", get_upload);
let not_found_catcher = Catcher::new(404, not_found_handler);
rocket::ignite()
.mount("/", vec![always_forward, hello, echo])
.mount("/upload", vec![get_upload, post_upload])
.mount("/hello", vec![name.clone()])
.mount("/hi", vec![name])
.catch(vec![not_found_catcher])
2017-01-09 02:02:12 +00:00
}
fn main() {
rocket().launch();
}