Skip to content

feat(http): Add reusable handler for scrape endpoints - #387

Open
kalleep wants to merge 4 commits into
prometheus:masterfrom
kalleep:http-handler
Open

kalleep wants to merge 4 commits into
prometheus:masterfrom
kalleep:http-handler

Conversation

@kalleep

@kalleep kalleep commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Adds http::ScrapeHandler, so a scrape endpoint doesn't have to wire up negotiation, encoding and the response headers itself.

let handler = ScrapeHandler::builder()
    .with_formats(&[Format::OpenMetricsText1_0_0, Format::PrometheusText0_0_4])
    .build();

match handler.handle(&registry, |name| {
    headers.get(name).and_then(|value| value.to_str().ok())
}) {
    Ok(response) => {
        // Copy response.status(), response.headers() and response.into_body()
        // into the response type of your HTTP framework.
    }
    Err(err) => {
        // Log err and respond with err.status().
    }
}

By default it offers every format that is supported and enabled with feature flags. with_formats changes the offered formats, and more options like compression or escaping can be added to the builder later without breaking anything.

handle takes a closure that looks up a request header by its lowercase name, so it works with any HTTP framework without adding dependencies. It returns a ScrapeResponse with the status, the Content-Type and Vary: Accept headers, and the encoded body. If encoding fails, it returns a ScrapeError with the status to respond with and the EncodeError as its source.

Fixes: #385

I updated the api a bit to return Result<ScrapeResponse, ScrapeError> so that caller can actually inspect the error.

Signed-off-by: Kalle <23356117+kalleep@users.noreply.github.com>
Signed-off-by: Kalle <23356117+kalleep@users.noreply.github.com>
Signed-off-by: Kalle <23356117+kalleep@users.noreply.github.com>
Signed-off-by: Kalle <23356117+kalleep@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add a reusable handler for answering scrapes over HTTP

1 participant