Update to latest Rocket master (#91)

- Update all instances of `State<T>` to borrow and drop anonymous lifetime
- Remove examples showing returning a `Response` instead of a `Responder`
  since `Response` no longer implements `Responder`
This commit is contained in:
Eric Dattore 2021-05-27 20:57:55 -06:00 committed by GitHub
parent 273522e697
commit 0b2d3e80b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 19 additions and 56 deletions

View File

@ -22,7 +22,7 @@ serialization = ["serde", "serde_derive", "unicase_serde"]
[dependencies] [dependencies]
regex = "1.1" regex = "1.1"
rocket = { rev="801e04bd5369eb39e126c75f6d11e1e9597304d8", git = "https://github.com/SergioBenitez/Rocket.git", default-features = false } rocket = { rev="1f1976f8bf8531daf4ac596d83ea7ad589dd7368", git = "https://github.com/SergioBenitez/Rocket.git", default-features = false }
log = "0.4" log = "0.4"
unicase = "2.0" unicase = "2.0"
url = "2.1.0" url = "2.1.0"

View File

@ -1,8 +1,6 @@
use std::error::Error; use std::error::Error;
use std::io::Cursor;
use rocket::http::Method; use rocket::http::Method;
use rocket::Response;
use rocket::{get, options, routes}; use rocket::{get, options, routes};
use rocket_cors::{AllowedHeaders, AllowedOrigins, Guard, Responder}; use rocket_cors::{AllowedHeaders, AllowedOrigins, Guard, Responder};
@ -12,15 +10,6 @@ fn responder(cors: Guard<'_>) -> Responder<'_, '_, &str> {
cors.responder("Hello CORS!") cors.responder("Hello CORS!")
} }
/// Using a `Response` instead of a `Responder`. You generally won't have to do this.
#[get("/response")]
fn response(cors: Guard<'_>) -> Response<'_> {
let mut response = Response::new();
let body = "Hello CORS!";
response.set_sized_body(body.len(), Cursor::new(body));
cors.response(response)
}
/// Manually mount an OPTIONS route for your own handling /// Manually mount an OPTIONS route for your own handling
#[options("/manual")] #[options("/manual")]
fn manual_options(cors: Guard<'_>) -> Responder<'_, '_, &str> { fn manual_options(cors: Guard<'_>) -> Responder<'_, '_, &str> {
@ -48,7 +37,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
.to_cors()?; .to_cors()?;
rocket::build() rocket::build()
.mount("/", routes![responder, response]) .mount("/", routes![responder])
// Mount the routes to catch all the OPTIONS pre-flight requests // Mount the routes to catch all the OPTIONS pre-flight requests
.mount("/", rocket_cors::catch_all_options_routes()) .mount("/", rocket_cors::catch_all_options_routes())
// You can also manually mount an OPTIONS route that will be used instead // You can also manually mount an OPTIONS route that will be used instead

View File

@ -1,9 +1,7 @@
use std::io::Cursor;
use rocket::error::Error; use rocket::error::Error;
use rocket::http::Method; use rocket::http::Method;
use rocket::response::Responder; use rocket::response::Responder;
use rocket::{get, options, routes, Response, State}; use rocket::{get, options, routes, State};
use rocket_cors::{AllowedHeaders, AllowedOrigins, Cors, CorsOptions}; use rocket_cors::{AllowedHeaders, AllowedOrigins, Cors, CorsOptions};
/// Using a borrowed Cors /// Using a borrowed Cors
@ -14,26 +12,12 @@ use rocket_cors::{AllowedHeaders, AllowedOrigins, Cors, CorsOptions};
/// Note that the `'r` lifetime annotation is not requred here because `State` borrows with lifetime /// Note that the `'r` lifetime annotation is not requred here because `State` borrows with lifetime
/// `'r` and so does `Responder`! /// `'r` and so does `Responder`!
#[get("/")] #[get("/")]
fn borrowed(options: State<'_, Cors>) -> impl Responder<'_, '_> { fn borrowed(options: &State<Cors>) -> impl Responder<'_, '_> {
options options
.inner() .inner()
.respond_borrowed(|guard| guard.responder("Hello CORS")) .respond_borrowed(|guard| guard.responder("Hello CORS"))
} }
/// Using a `Response` instead of a `Responder`. You generally won't have to do this.
/// Note that the `'r` lifetime annotation is not requred here because `State` borrows with lifetime
/// `'r` and so does `Responder`!
#[get("/response")]
fn response(options: State<'_, Cors>) -> impl Responder<'_, '_> {
let mut response = Response::new();
let body = "Hello CORS!";
response.set_sized_body(body.len(), Cursor::new(body));
options
.inner()
.respond_borrowed(move |guard| guard.response(response))
}
/// Create and use an ad-hoc Cors /// Create and use an ad-hoc Cors
/// Note that the `'r` lifetime is needed because the compiler cannot elide anything. /// Note that the `'r` lifetime is needed because the compiler cannot elide anything.
/// ///
@ -72,7 +56,7 @@ fn cors_options() -> CorsOptions {
#[rocket::main] #[rocket::main]
async fn main() -> Result<(), Error> { async fn main() -> Result<(), Error> {
rocket::build() rocket::build()
.mount("/", routes![borrowed, response, owned, owned_options,]) .mount("/", routes![borrowed, owned, owned_options,])
.mount("/", rocket_cors::catch_all_options_routes()) // mount the catch all routes .mount("/", rocket_cors::catch_all_options_routes()) // mount the catch all routes
.manage(cors_options().to_cors().expect("To not fail")) .manage(cors_options().to_cors().expect("To not fail"))
.launch() .launch()

View File

@ -93,7 +93,7 @@ fn on_response_wrapper(
request request
); );
response.set_status(Status::NoContent); response.set_status(Status::NoContent);
let _ = response.take_body(); let _ = response.body();
} }
Ok(()) Ok(())
} }
@ -134,7 +134,7 @@ impl rocket::fairing::Fairing for Cors {
if let Err(err) = on_response_wrapper(self, request, response) { if let Err(err) = on_response_wrapper(self, request, response) {
error_!("Fairings on_response error: {}\nMost likely a bug", err); error_!("Fairings on_response error: {}\nMost likely a bug", err);
response.set_status(Status::InternalServerError); response.set_status(Status::InternalServerError);
let _ = response.take_body(); let _ = response.body();
} }
} }
} }

View File

@ -124,7 +124,7 @@ impl FromStr for Origin {
} }
impl fmt::Display for Origin { impl fmt::Display for Origin {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Origin::Null => write!(f, "null"), Origin::Null => write!(f, "null"),
Origin::Parsed(ref parsed) => write!(f, "{}", parsed.ascii_serialization()), Origin::Parsed(ref parsed) => write!(f, "{}", parsed.ascii_serialization()),

View File

@ -353,7 +353,7 @@ impl Error {
} }
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Error::MissingOrigin => write!( Error::MissingOrigin => write!(
f, f,
@ -1521,7 +1521,7 @@ impl<'r> FromRequest<'r> for Guard<'r> {
type Error = Error; type Error = Error;
async fn from_request(request: &'r Request<'_>) -> rocket::request::Outcome<Self, Self::Error> { async fn from_request(request: &'r Request<'_>) -> rocket::request::Outcome<Self, Self::Error> {
let options = match request.guard::<State<'_, Cors>>().await { let options = match request.guard::<&State<Cors>>().await {
Outcome::Success(options) => options, Outcome::Success(options) => options,
_ => { _ => {
let error = Error::MissingCorsInRocketState; let error = Error::MissingCorsInRocketState;
@ -2523,8 +2523,7 @@ mod tests {
let response = Response::new(); let response = Response::new();
let response = response.response(response::Response::new()); let response = response.response(response::Response::new());
let headers: Vec<_> = response.headers().iter().collect(); assert_eq!(response.headers().iter().count(), 0);
assert_eq!(headers.len(), 0);
} }
#[test] #[test]

View File

@ -5,8 +5,8 @@ use rocket::http::hyper;
use rocket::http::Method; use rocket::http::Method;
use rocket::http::{Header, Status}; use rocket::http::{Header, Status};
use rocket::local::blocking::Client; use rocket::local::blocking::Client;
use rocket::State;
use rocket::{get, options, routes}; use rocket::{get, options, routes};
use rocket::{Response, State};
static ORIGIN: hyper::HeaderName = hyper::header::ORIGIN; static ORIGIN: hyper::HeaderName = hyper::header::ORIGIN;
static ACCESS_CONTROL_REQUEST_METHOD: hyper::HeaderName = static ACCESS_CONTROL_REQUEST_METHOD: hyper::HeaderName =
@ -36,12 +36,6 @@ fn cors_manual(cors: cors::Guard<'_>) -> cors::Responder<'_, '_, &str> {
cors.responder("Hello CORS") cors.responder("Hello CORS")
} }
/// Using a `Response` instead of a `Responder`
#[get("/response")]
fn response(cors: cors::Guard<'_>) -> Response<'_> {
cors.response(Response::new())
}
/// `Responder` with String /// `Responder` with String
#[get("/responder/string")] #[get("/responder/string")]
fn responder_string(cors: cors::Guard<'_>) -> cors::Responder<'_, 'static, String> { fn responder_string(cors: cors::Guard<'_>) -> cors::Responder<'_, 'static, String> {
@ -59,7 +53,7 @@ struct SomeState;
#[get("/state")] #[get("/state")]
fn state<'r, 'o: 'r>( fn state<'r, 'o: 'r>(
cors: cors::Guard<'r>, cors: cors::Guard<'r>,
_state: State<'r, SomeState>, _state: &State<SomeState>,
) -> cors::Responder<'r, 'o, &'r str> { ) -> cors::Responder<'r, 'o, &'r str> {
cors.responder("hmm") cors.responder("hmm")
} }
@ -81,10 +75,7 @@ fn make_cors() -> cors::Cors {
fn make_rocket() -> rocket::Rocket<rocket::Build> { fn make_rocket() -> rocket::Rocket<rocket::Build> {
rocket::build() rocket::build()
.mount("/", routes![cors_responder, panicking_route]) .mount("/", routes![cors_responder, panicking_route])
.mount( .mount("/", routes![responder_string, responder_unit, state])
"/",
routes![response, responder_string, responder_unit, state],
)
.mount("/", cors::catch_all_options_routes()) // mount the catch all routes .mount("/", cors::catch_all_options_routes()) // mount the catch all routes
.mount("/", routes![cors_manual, cors_manual_options]) // manual OPTIOONS routes .mount("/", routes![cors_manual, cors_manual_options]) // manual OPTIOONS routes
.manage(make_cors()) .manage(make_cors())

View File

@ -16,14 +16,14 @@ static ACCESS_CONTROL_REQUEST_HEADERS: hyper::HeaderName =
/// Using a borrowed `Cors` /// Using a borrowed `Cors`
#[get("/")] #[get("/")]
fn cors(options: State<'_, Cors>) -> impl Responder<'_, '_> { fn cors(options: &State<Cors>) -> impl Responder<'_, '_> {
options options
.inner() .inner()
.respond_borrowed(|guard| guard.responder("Hello CORS")) .respond_borrowed(|guard| guard.responder("Hello CORS"))
} }
#[get("/panic")] #[get("/panic")]
fn panicking_route(options: State<'_, Cors>) -> impl Responder<'_, '_> { fn panicking_route(options: &State<Cors>) -> impl Responder<'_, '_> {
options.inner().respond_borrowed(|_| { options.inner().respond_borrowed(|_| {
panic!("This route will panic"); panic!("This route will panic");
}) })
@ -50,7 +50,7 @@ fn owned<'r, 'o: 'r>() -> impl Responder<'r, 'o> {
/// `Responder` with String /// `Responder` with String
#[get("/")] #[get("/")]
#[allow(dead_code)] #[allow(dead_code)]
fn responder_string(options: State<'_, Cors>) -> impl Responder<'_, '_> { fn responder_string(options: &State<Cors>) -> impl Responder<'_, '_> {
options options
.inner() .inner()
.respond_borrowed(|guard| guard.responder("Hello CORS".to_string())) .respond_borrowed(|guard| guard.responder("Hello CORS".to_string()))
@ -61,8 +61,8 @@ struct TestState;
#[get("/")] #[get("/")]
#[allow(dead_code)] #[allow(dead_code)]
fn borrow<'r, 'o: 'r>( fn borrow<'r, 'o: 'r>(
options: State<'r, Cors>, options: &'r State<Cors>,
test_state: State<'r, TestState>, test_state: &'r State<TestState>,
) -> impl Responder<'r, 'o> { ) -> impl Responder<'r, 'o> {
let borrow = test_state.inner(); let borrow = test_state.inner();
options.inner().respond_borrowed(move |guard| { options.inner().respond_borrowed(move |guard| {