Expand description
§vld-http-common — Shared HTTP helpers for vld web integrations
This crate provides the common parsing helpers and the shared
VldHttpError type used by vld-actix, vld-axum, vld-ntex,
vld-poem, vld-rama, vld-rocket, vld-salvo, vld-tower,
vld-warp and vld-tonic.
Applications normally use it through a framework adapter. Depend on it
directly to write an adapter for another framework or to build the same
error body by hand. It is framework-agnostic: no HTTP framework or http
crate dependency.
Guide: https://s00d.github.io/vld/integrations/shared/http-common (the rules below, per framework: https://s00d.github.io/vld/integrations/web/overview).
§Example
use vld_http_common::{parse_json_body, require_json_content_type, VldHttpError};
vld::schema! {
#[derive(Debug)]
pub struct User {
pub name: String => vld::string().min(2),
}
}
fn extract(content_type: Option<&str>, body: &[u8]) -> Result<User, VldHttpError> {
require_json_content_type(content_type)?; // 415
let value = parse_json_body(body)?; // 422 on malformed JSON
Ok(User::parse_value(&value)?) // 422 on validation errors
}
let err = extract(Some("application/json"), br#"{"name": "A"}"#).unwrap_err();
assert_eq!(err.status(), 422);
assert_eq!(err.body()["issues"][0]["code"], "too_small");
assert_eq!(extract(Some("text/plain"), b"{}").unwrap_err().status(), 415);
// Text sources (query, form, path, headers, cookies) use `parse_coerced`.
vld::schema! {
#[derive(Debug)]
pub struct Search {
pub q: String => vld::string(),
pub page: i64 => vld::number().int().min(1),
pub tags: Vec<String> => vld::array(vld::string()),
}
}
let value = vld_http_common::query_string_to_json("q=123&page=2&tags=a");
let s: Search = vld_http_common::parse_coerced(&value).unwrap();
assert_eq!((s.q.as_str(), s.page, s.tags.len()), ("123", 2, 1));§Value semantics (all adapters)
- Query strings and form bodies: repeated keys (
a=1&a=2) anda[]=1become arrays;?flagand?x=become"". - Values are coerced with
coerce_value, which never loses information. - Coerced sources are validated with
parse_coerced: a coerced number / boolean is turned back into text where the schema expects a string (?q=123intovld::string()is"123"), and a single value is wrapped into an array where the schema expects one (?tags=a). - JSON body extractors require a JSON
Content-Type(application/jsonorapplication/*+json, seeis_json_content_type) and form extractorsapplication/x-www-form-urlencoded(require_form_content_type); a missing or different type is 415{"error": "Unsupported Media Type", "message": ...}. - Malformed bodies (JSON, non-UTF-8 forms, more than
MAX_FORM_FIELDSform fields) → 422 with theValidationErrorBodyshape; oversized bodies → 413{"error": "Payload too large"}. - Header names containing
_are ignored (seeheaders_to_json); allCookieheaders are read and the first occurrence of a cookie name wins (seecookie_headers_to_json).
§Error bodies
| Status | Body |
|---|---|
| 422 | {"error": "Validation failed", "issues": [{"path": ".name", "message": "...", "code": "too_small"}]} |
| 413 | {"error": "Payload too large"} |
| 415 | {"error": "Unsupported Media Type", "message": "Expected Content-Type: ..."} |
path is "" for the root (e.g. malformed JSON), .field for fields and
[0] for array items (.items[0].name); code is
IssueCode::key().
Structs§
- Error
Body - Simple error body:
{ "error": "..." }. - Error
With Message - Error body with a message:
{ "error": "...", "message": "..." }. - Validation
Error Body - Validation error response body:
{ "error": "Validation failed", "issues": [...] }. - Validation
Issue - A single validation issue:
{ "path": "...", "message": "...", "code": "..." }(codeisIssueCode::key()). - VldBody
Limit - Body size limit in bytes, registered as request/app data for the adapters
without a framework-native body limit setting (
vld-actixapp_data,vld-ntexapp state,vld-poem.data(..);vld-ramahas its own extension type). - VldHttp
Error - Framework-independent error produced by all
vldHTTP adapters.
Constants§
- DEFAULT_
BODY_ LIMIT - Default max request body size (2 MiB — same as axum
DefaultBodyLimit). - MAX_
FORM_ FIELDS - Max number of
&-separated fields in a form body (parse_form_body). - UNSUPPORTED_
FORM_ MEDIA_ TYPE_ MESSAGE - Message of the 415 body and error for form extractors.
- UNSUPPORTED_
MEDIA_ TYPE_ MESSAGE - Message of the 415 body and error for JSON extractors.
Functions§
- coerce_
value - Coerce a raw string value (query, form, path, header, cookie) into JSON.
- cookie_
headers_ to_ json - Build a JSON object from all
Cookieheader values of a request. - cookies_
to_ json - Build a JSON object from a
Cookieheader value. - format_
generic_ error - Build a generic JSON error body with a custom error string.
- format_
issues - Format a
VldErrorinto a list ofValidationIssuestructs. - format_
payload_ too_ large - Build a JSON error body for payloads that exceed the size limit.
- format_
unsupported_ media_ type - Build the JSON error body for a non-JSON
Content-Type. - format_
vld_ error - Format a
VldErrorinto a JSON object with"error"and"issues"keys — ready to be sent as a 422 response body. - headers_
to_ json - Build a JSON object from HTTP header name/value pairs.
- is_
json_ content_ type trueforapplication/jsonand anyapplication/<x>+jsonmedia type with a non-empty<x>(case-insensitive; parameters such as; charset=utf-8are ignored, even malformed ones).- parse_
coerced - Parse a value whose leaves were coerced from text (
"42"→42,"true"→true), undoing the coercion where the schema disagrees. - parse_
form_ body - Parse an
application/x-www-form-urlencodedbody. - parse_
json_ body - Parse a JSON body; malformed JSON is a 422 parse error.
- parse_
query_ string - Parse a URL query string (or
application/x-www-form-urlencodedbody) into aserde_json::Map. - path_
params_ to_ json - Build a JSON object from already-decoded path parameters, coercing each
value via
coerce_value. - percent_
decode - Percent-decode a URL component (path segment, cookie value);
+is kept. - query_
string_ to_ json - Parse a URL query string into a
serde_json::Value::Object. - require_
form_ content_ type - Check the
Content-Typeof a form body:Okforapplication/x-www-form-urlencoded(case-insensitive, parameters allowed), otherwise a 415 error (also when the header is missing or not valid UTF-8). - require_
json_ content_ type - Check the
Content-Typeof a JSON body:Okfor JSON media types (is_json_content_type), otherwise a 415 error (also when the header is missing or not valid UTF-8). - url_
decode - Decode a form/query component:
+→ space, thenpercent_decode.