headers.rs (2267B)
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(&'static str), 23 #[error("Malformed header {0} expected string got binary")] 24 NotStr(&'static str), 25 #[error("Malformed header {0} expected {1} got '{2}'")] 26 Malformed(&'static str, &'static str, Box<str>), 27 } 28 29 pub trait HeaderParser { 30 fn parse<T>( 31 &self, 32 name: &'static str, 33 kind: &'static str, 34 transform: impl FnOnce(&str) -> Result<T, ()>, 35 ) -> Result<T, HeaderError>; 36 fn str_header(&self, name: &'static str) -> Result<String, HeaderError> { 37 self.parse(name, "string", |s| Ok(s.to_owned())) 38 } 39 fn int_header(&self, name: &'static str) -> Result<u64, HeaderError> { 40 self.parse(name, "integer", |s| s.parse().map_err(|_| ())) 41 } 42 fn bool_header(&self, name: &'static str) -> Result<bool, HeaderError> { 43 self.parse(name, "boolean", |s| s.parse().map_err(|_| ())) 44 } 45 } 46 47 impl HeaderParser for HeaderMap { 48 fn parse<T>( 49 &self, 50 name: &'static str, 51 kind: &'static str, 52 transform: impl FnOnce(&str) -> Result<T, ()>, 53 ) -> Result<T, HeaderError> { 54 let Some(value) = self.get(HeaderName::from_static(name)) else { 55 return Err(HeaderError::Missing(name)); 56 }; 57 let Ok(str) = value.to_str() else { 58 return Err(HeaderError::NotStr(name)); 59 }; 60 transform(str).map_err(|_| HeaderError::Malformed(name, kind, str.into())) 61 } 62 }