Skip to main content

systemprompt_api/services/middleware/context/sources/
headers.rs

1//! Request-context extraction from `x-*` headers.
2//!
3//! Copyright (c) systemprompt.io — Business Source License 1.1.
4//! See <https://systemprompt.io> for licensing details.
5
6use axum::http::HeaderMap;
7use systemprompt_models::execution::ContextExtractionError;
8
9#[derive(Debug, Clone, Copy)]
10pub struct HeaderSource;
11
12impl HeaderSource {
13    pub fn extract_required(
14        headers: &HeaderMap,
15        name: &str,
16    ) -> Result<String, ContextExtractionError> {
17        headers
18            .get(name)
19            .ok_or_else(|| ContextExtractionError::MissingHeader(name.to_owned()))?
20            .to_str()
21            .map(str::to_owned)
22            .map_err(|e| ContextExtractionError::InvalidHeaderValue {
23                header: name.to_owned(),
24                reason: e.to_string(),
25            })
26    }
27
28    pub fn extract_optional(headers: &HeaderMap, name: &str) -> Option<String> {
29        headers
30            .get(name)
31            .and_then(|v| v.to_str().ok())
32            .map(str::to_owned)
33    }
34}