headers.rs (2290B)
1 /* 2 This file is part of TALER 3 Copyright (C) 2026 Taler Systems SA 4 5 TALER is free software; you can redistribute it and/or modify it under the 6 terms of the GNU Affero General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 TALER is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 12 13 You should have received a copy of the GNU Affero General Public License along with 14 TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 use hyper::{HeaderMap, header::HeaderName}; 18 19 #[derive(Debug, thiserror::Error)] 20 pub enum HeaderError { 21 #[error("Missing header {0}")] 22 Missing(HeaderName), 23 #[error("Malformed header {0} expected string got binary")] 24 NotStr(HeaderName), 25 #[error("Malformed header {0} expected {1} got '{2}'")] 26 Malformed(HeaderName, &'static str, Box<str>), 27 } 28 29 pub trait HeaderParser<E> { 30 fn parse<T>( 31 &self, 32 name: impl Into<HeaderName>, 33 kind: &'static str, 34 transform: impl FnOnce(&str) -> Result<T, ()>, 35 ) -> Result<T, E>; 36 fn str_header(&self, name: impl Into<HeaderName>) -> Result<String, E> { 37 self.parse(name, "string", |s| Ok(s.to_owned())) 38 } 39 fn int_header(&self, name: impl Into<HeaderName>) -> Result<u64, E> { 40 self.parse(name, "integer", |s| s.parse().map_err(|_| ())) 41 } 42 fn bool_header(&self, name: impl Into<HeaderName>) -> Result<bool, E> { 43 self.parse(name, "boolean", |s| s.parse().map_err(|_| ())) 44 } 45 } 46 47 impl HeaderParser<HeaderError> for HeaderMap { 48 fn parse<T>( 49 &self, 50 name: impl Into<HeaderName>, 51 kind: &'static str, 52 transform: impl FnOnce(&str) -> Result<T, ()>, 53 ) -> Result<T, HeaderError> { 54 let name = name.into(); 55 let Some(value) = self.get(&name) else { 56 return Err(HeaderError::Missing(name)); 57 }; 58 let Ok(str) = value.to_str() else { 59 return Err(HeaderError::NotStr(name)); 60 }; 61 transform(str).map_err(|_| HeaderError::Malformed(name, kind, str.into())) 62 } 63 }