Compare commits

...

5 Commits

Author SHA1 Message Date
Maarten Deprez f01ccf7db0
Merge 116f7d13b0 into d119500f93 2025-11-16 15:54:53 +09:00
Yuki Okushi d119500f93
release: actix-web v4.12.0 (#3830) 2025-11-16 15:52:36 +09:00
Yuki Okushi a3f95ee1ef
feat: improve `HttpResponseBuilder::streaming` with SizedStream (#3829) 2025-11-16 15:22:29 +09:00
Maarten Deprez 116f7d13b0 Support deserializing paths to sequences: use "/{tail}*" syntax 2024-08-15 17:05:26 +02:00
Maarten Deprez feee43094e Support deserializing paths to sequences for multi-component (eg. tail) matches 2024-08-15 16:54:51 +02:00
8 changed files with 138 additions and 19 deletions

2
Cargo.lock generated
View File

@ -345,7 +345,7 @@ dependencies = [
[[package]]
name = "actix-web"
version = "4.11.0"
version = "4.12.0"
dependencies = [
"actix-codec",
"actix-files",

View File

@ -5,6 +5,7 @@
## 0.5.3
- Add `unicode` crate feature (on-by-default) to switch between `regex` and `regex-lite` as a trade-off between full unicode support and binary size.
- Add support for extracting multi-component path params into a sequence (Vec, tuple, ...)
- Minimum supported Rust version (MSRV) is now 1.72.
## 0.5.2

View File

@ -396,11 +396,25 @@ impl<'de> Deserializer<'de> for Value<'de> {
visitor.visit_newtype_struct(self)
}
fn deserialize_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(de::value::Error::custom("unsupported type: tuple"))
let value_seq = ValueSeq::new(self.value);
if len == value_seq.len() {
visitor.visit_seq(value_seq)
} else {
Err(de::value::Error::custom(
"path and tuple lengths don't match",
))
}
}
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_seq(ValueSeq::new(self.value))
}
fn deserialize_struct<V>(
@ -428,7 +442,6 @@ impl<'de> Deserializer<'de> for Value<'de> {
}
unsupported_type!(deserialize_any, "any");
unsupported_type!(deserialize_seq, "seq");
unsupported_type!(deserialize_map, "map");
unsupported_type!(deserialize_identifier, "identifier");
}
@ -498,6 +511,45 @@ impl<'de> de::VariantAccess<'de> for UnitVariant {
}
}
struct ValueSeq<'de> {
value: &'de str,
elems: std::str::Split<'de, char>,
}
impl<'de> ValueSeq<'de> {
fn new(value: &'de str) -> Self {
Self {
value,
elems: value.split('/'),
}
}
fn len(&self) -> usize {
self.value.split('/').filter(|s| !s.is_empty()).count()
}
}
impl<'de> de::SeqAccess<'de> for ValueSeq<'de> {
type Error = de::value::Error;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
for elem in &mut self.elems {
if !elem.is_empty() {
return seed.deserialize(Value { value: elem }).map(Some);
}
}
Ok(None)
}
fn size_hint(&self) -> Option<usize> {
Some(self.len())
}
}
#[cfg(test)]
mod tests {
use serde::Deserialize;
@ -532,6 +584,16 @@ mod tests {
val: TestEnum,
}
#[derive(Debug, Deserialize)]
struct TestSeq1 {
tail: Vec<String>,
}
#[derive(Debug, Deserialize)]
struct TestSeq2 {
tail: (String, String, String),
}
#[test]
fn test_request_extract() {
let mut router = Router::<()>::build();
@ -627,6 +689,39 @@ mod tests {
assert!(format!("{:?}", i).contains("unknown variant"));
}
#[test]
fn test_extract_seq() {
let mut router = Router::<()>::build();
router.path("/path/to/{tail}*", ());
let router = router.finish();
let mut path = Path::new("/path/to/tail/with/slash%2fes");
assert!(router.recognize(&mut path).is_some());
let i: (String,) = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(i.0, String::from("tail/with/slash/es"));
let i: TestSeq1 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(
i.tail,
vec![
String::from("tail"),
String::from("with"),
String::from("slash/es")
]
);
let i: TestSeq2 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(
i.tail,
(
String::from("tail"),
String::from("with"),
String::from("slash/es")
)
);
}
#[test]
fn test_extract_errors() {
let mut router = Router::<()>::build();

View File

@ -2,8 +2,10 @@
## Unreleased
## 4.12.0
- `actix_web::response::builder::HttpResponseBuilder::streaming()` now sets `Content-Type` to `application/octet-stream` if `Content-Type` does not exist.
- `actix_web::response::builder::HttpResponseBuilder::streaming()` now calls `actix_web::response::builder::HttpResponseBuilder::no_chunking()` if `Content-Length` is set by user.
- `actix_web::response::builder::HttpResponseBuilder::streaming()` now calls `actix_web::response::builder::HttpResponseBuilder::no_chunking()` and returns `SizedStream` if `Content-Length` is set by user.
- Add `ws` crate feature (on-by-default) which forwards to `actix-http` and guards some of its `ResponseError` impls.
- Add public export for `EitherExtractError` in `error` module.

View File

@ -1,6 +1,6 @@
[package]
name = "actix-web"
version = "4.11.0"
version = "4.12.0"
description = "Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust"
authors = ["Nikolay Kim <fafhrd91@gmail.com>", "Rob Ede <robjtede@icloud.com>"]
keywords = ["actix", "http", "web", "framework", "async"]

View File

@ -8,10 +8,10 @@
<!-- prettier-ignore-start -->
[![crates.io](https://img.shields.io/crates/v/actix-web?label=latest)](https://crates.io/crates/actix-web)
[![Documentation](https://docs.rs/actix-web/badge.svg?version=4.11.0)](https://docs.rs/actix-web/4.11.0)
[![Documentation](https://docs.rs/actix-web/badge.svg?version=4.12.0)](https://docs.rs/actix-web/4.12.0)
![MSRV](https://img.shields.io/badge/rustc-1.72+-ab6000.svg)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-web.svg)
[![Dependency Status](https://deps.rs/crate/actix-web/4.11.0/status.svg)](https://deps.rs/crate/actix-web/4.11.0)
[![Dependency Status](https://deps.rs/crate/actix-web/4.12.0/status.svg)](https://deps.rs/crate/actix-web/4.12.0)
<br />
[![CI](https://github.com/actix/actix-web/actions/workflows/ci.yml/badge.svg)](https://github.com/actix/actix-web/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/actix/actix-web/graph/badge.svg?token=dSwOnp9QCv)](https://codecov.io/gh/actix/actix-web)

View File

@ -11,7 +11,7 @@ use futures_core::Stream;
use serde::Serialize;
use crate::{
body::{BodyStream, BoxBody, MessageBody},
body::{BodyStream, BoxBody, MessageBody, SizedStream},
dev::Extensions,
error::{Error, JsonPayloadError},
http::{
@ -335,17 +335,18 @@ impl HttpResponseBuilder {
}
}
if let Some(parts) = self.inner() {
if let Some(length) = parts.headers.get(header::CONTENT_LENGTH) {
if let Ok(length) = length.to_str() {
if let Ok(length) = length.parse::<u64>() {
self.no_chunking(length);
}
}
}
}
let content_length = self
.inner()
.and_then(|parts| parts.headers.get(header::CONTENT_LENGTH))
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<u64>().ok());
self.body(BodyStream::new(stream))
if let Some(len) = content_length {
self.no_chunking(len);
self.body(SizedStream::new(len, stream))
} else {
self.body(BodyStream::new(stream))
}
}
/// Set a JSON body and build the `HttpResponse`.

View File

@ -53,6 +53,26 @@ use crate::{
/// format!("Welcome {}!", info.name)
/// }
/// ```
///
/// Segments matching multiple path components can be deserialized
/// into a Vec<_> to percent-decode the components individually. Empty
/// path components are ignored.
///
/// ```
/// use actix_web::{get, web};
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Tail {
/// tail: Vec<String>,
/// }
///
/// // extract `Tail` from a path using serde
/// #[get("/path/to/{tail}*")]
/// async fn index(info: web::Path<Tail>) -> String {
/// format!("Navigating to {}!", info.tail.join(" :: "))
/// }
/// ```
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Deref, DerefMut, AsRef, Display, From)]
pub struct Path<T>(T);