How to extract custom Header #1437
-
Hello people, thanks for this awesome framework. I've been struggling to extract a custom header. I'm trying to parse a git webhook with header #[derive(Deserialize, Debug, Clone)]
enum EventKey {
RepoPush,
}
impl FromStr for EventKey {
type Err = AppError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"repo:push" => Ok(Self::RepoPush),
_ => Err(AppError::InvalidHeader),
}
}
}
async fn webhook_handler(event_type: TypedHeader<EventKey>) -> Response {
println!("{event_type:?}");
return (StatusCode::OK, String::from("Ok")).into_response();
} The error I get:
I'm now trying to implement the Thanks in advance!! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Don't bother with |
Beta Was this translation helpful? Give feedback.
-
for anyone stumbling upon this in 2025 (and probably later?), here's how you can define a custom string header that works with axum extractors: macro_rules! define_string_header {
($type_name:ident, $header_str:expr) => {
pub struct $type_name {
value: String,
}
impl ::headers::Header for $type_name {
fn name() -> &'static ::axum::http::HeaderName {
static HEADER_NAME: ::axum::http::HeaderName =
::axum::http::HeaderName::from_static($header_str);
&HEADER_NAME
}
fn decode<'i, I>(values: &mut I) -> Result<Self, ::headers::Error>
where
Self: Sized,
I: Iterator<Item = &'i ::axum::http::HeaderValue>,
{
let value = values
.next()
.ok_or_else(::headers::Error::invalid)?
.to_str()
.map_err(|_| ::headers::Error::invalid())?
.to_string();
Ok(Self { value })
}
fn encode<E: Extend<axum::http::HeaderValue>>(&self, values: &mut E) {
values.extend(std::iter::once(
self.value.parse().expect("failed to encode header"),
));
}
}
impl std::fmt::Display for $type_name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.value)
}
}
};
}
define_string_header!(MyHeader, "x-my-header"); |
Beta Was this translation helpful? Give feedback.
Don't bother with
TypedHeader
for something like this. Either write your ownFromRequest
implementation or extractHeaderMap
directly.