Created
December 26, 2023 01:14
-
-
Save DefectingCat/a1bcc8aa3ec8e30141a2493966ec41a1 to your computer and use it in GitHub Desktop.
Axum custom add version for each response middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use crate::error::AppResult; | |
use anyhow::anyhow; | |
use axum::{ | |
body::Body, extract::Request, http::HeaderValue, middleware::Next, response::IntoResponse, | |
}; | |
/// Middleware for adding version information to each response's headers. | |
/// | |
/// This middleware takes an incoming `Request` and a `Next` handler, which represents the | |
/// subsequent middleware or route in the chain. It then asynchronously runs the next handler, | |
/// obtaining the response. After receiving the response, it appends two headers: | |
/// - "Server": The name of the server extracted from the Cargo package name. | |
/// - "S-Version": The version of the server extracted from the Cargo package version. | |
pub async fn add_version(req: Request<Body>, next: Next) -> AppResult<impl IntoResponse> { | |
let mut res = next.run(req).await; | |
let headers = res.headers_mut(); | |
headers.append( | |
"Server", | |
HeaderValue::from_str(env!("CARGO_PKG_NAME")).map_err(|err| anyhow!("{}", err))?, | |
); | |
headers.append( | |
"S-Version", | |
HeaderValue::from_str(env!("CARGO_PKG_VERSION")).map_err(|err| anyhow!("{}", err))?, | |
); | |
Ok(res) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment