Use RequestPartsExt more in docs / examples (#1445)

* Use RequestPartsExt more in docs / examples

* Remove unused import
This commit is contained in:
Jonas Platte 2022-10-04 19:26:51 +02:00 committed by GitHub
parent a57bd9a118
commit a7d8954178
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 31 additions and 31 deletions

View file

@ -595,17 +595,19 @@ where
type Rejection = Response;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
// You can either call them directly...
let TypedHeader(Authorization(token)) =
TypedHeader::<Authorization<Bearer>>::from_request_parts(parts, state)
.await
.map_err(|err| err.into_response())?;
let Extension(state): Extension<State> = Extension::from_request_parts(parts, state)
// ... or use `extract` / `extract_with_state` from `RequestExt` / `RequestPartsExt`
use axum::RequestPartsExt;
let Extension(state) = parts.extract::<Extension<State>>()
.await
.map_err(|err| err.into_response())?;
// actually perform the authorization...
unimplemented!()
unimplemented!("actually perform the authorization")
}
}
@ -710,12 +712,12 @@ Extractors can also be run from middleware:
```rust
use axum::{
Router,
middleware::{self, Next},
extract::{TypedHeader, FromRequestParts},
http::{Request, StatusCode},
response::Response,
headers::authorization::{Authorization, Bearer},
RequestPartsExt, Router,
};
async fn auth_middleware<B>(
@ -729,7 +731,7 @@ where
let (mut parts, body) = request.into_parts();
// `TypedHeader<Authorization<Bearer>>` extracts the auth token
let auth = TypedHeader::<Authorization<Bearer>>::from_request_parts(&mut parts, &())
let auth: TypedHeader<Authorization<Bearer>> = parts.extract()
.await
.map_err(|_| StatusCode::UNAUTHORIZED)?;

View file

@ -6,10 +6,11 @@
//! - Complexity: Manually implementing `FromRequest` results on more complex code
use axum::{
async_trait,
extract::{rejection::JsonRejection, FromRequest, FromRequestParts, MatchedPath},
extract::{rejection::JsonRejection, FromRequest, MatchedPath},
http::Request,
http::StatusCode,
response::IntoResponse,
RequestPartsExt,
};
use serde_json::{json, Value};
@ -32,14 +33,13 @@ where
async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection> {
let (mut parts, body) = req.into_parts();
// We can use other extractors to provide better rejection
// messages. For example, here we are using
// `axum::extract::MatchedPath` to provide a better error
// message
// We can use other extractors to provide better rejection messages.
// For example, here we are using `axum::extract::MatchedPath` to
// provide a better error message.
//
// Have to run that first since `Json::from_request` consumes
// the request
let path = MatchedPath::from_request_parts(&mut parts, state)
// Have to run that first since `Json` extraction consumes the request.
let path = parts
.extract::<MatchedPath>()
.await
.map(|path| path.as_str().to_owned())
.ok();

View file

@ -5,7 +5,7 @@
//! ```
use axum::response::{IntoResponse, Response};
use axum::{http, routing::get, Router, RouterService};
use axum::{http, routing::get, Router};
use std::net::SocketAddr;
fn app() -> Router {

View file

@ -13,7 +13,7 @@ use axum::{
http::{request::Parts, StatusCode},
response::{IntoResponse, Response},
routing::{get, post},
Json, Router,
Json, RequestPartsExt, Router,
};
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use once_cell::sync::Lazy;
@ -128,10 +128,10 @@ where
{
type Rejection = AuthError;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
// Extract the token from the authorization header
let TypedHeader(Authorization(bearer)) =
TypedHeader::<Authorization<Bearer>>::from_request_parts(parts, state)
let TypedHeader(Authorization(bearer)) = parts
.extract::<TypedHeader<Authorization<Bearer>>>()
.await
.map_err(|_| AuthError::InvalidToken)?;
// Decode the user data

View file

@ -17,7 +17,7 @@ use axum::{
http::{header::SET_COOKIE, HeaderMap},
response::{IntoResponse, Redirect, Response},
routing::get,
Router,
RequestPartsExt, Router,
};
use http::{header, request::Parts};
use oauth2::{
@ -234,7 +234,8 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let store = MemoryStore::from_ref(state);
let cookies = TypedHeader::<headers::Cookie>::from_request_parts(parts, state)
let cookies = parts
.extract::<TypedHeader<headers::Cookie>>()
.await
.map_err(|e| match *e.name() {
header::COOKIE => match e.reason() {

View file

@ -17,7 +17,7 @@ use axum::{
},
response::IntoResponse,
routing::get,
Router,
RequestPartsExt, Router,
};
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
@ -91,9 +91,7 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let store = MemoryStore::from_ref(state);
let cookie = Option::<TypedHeader<Cookie>>::from_request_parts(parts, state)
.await
.unwrap();
let cookie: Option<TypedHeader<Cookie>> = parts.extract().await.unwrap();
let session_cookie = cookie
.as_ref()

View file

@ -10,7 +10,7 @@ use axum::{
http::{request::Parts, StatusCode},
response::{IntoResponse, Response},
routing::get,
Router,
RequestPartsExt, Router,
};
use std::{collections::HashMap, net::SocketAddr};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
@ -54,10 +54,9 @@ where
{
type Rejection = Response;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let params = Path::<HashMap<String, String>>::from_request_parts(parts, state)
.await
.map_err(IntoResponse::into_response)?;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let params: Path<HashMap<String, String>> =
parts.extract().await.map_err(IntoResponse::into_response)?;
let version = params
.get("version")