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(
23                |_not_visible_ascii| ContextExtractionError::InvalidHeaderValue {
24                    header: name.to_owned(),
25                    reason: "header value is not visible ASCII".to_owned(),
26                },
27            )
28    }
29
30    pub fn extract_optional(headers: &HeaderMap, name: &str) -> Option<String> {
31        headers
32            .get(name)
33            .and_then(|v| v.to_str().ok())
34            .map(str::to_owned)
35    }
36}