1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-07-04 01:51:30 +02:00

Compare commits

..

91 Commits

Author SHA1 Message Date
2b8c528e54 chore(actix-web): prepare release 4.5.1 2024-02-04 01:22:36 +00:00
59bc85fe0e chore(actix-http-test): prepare release 3.2.0 2024-02-04 00:34:00 +00:00
3f2fd2d59f chore(actix-test): prepare release 0.1.3 2024-02-04 00:33:42 +00:00
17ed73b33e chore(actix-web-actors): prepare release 4.3.0 2024-02-04 00:33:38 +00:00
73fa1184f1 chore(awc): prepare release 3.4.0 2024-02-04 00:32:57 +00:00
8e9e9fbcdd chore(actix-web): prepare release 4.5.0 2024-02-04 00:32:28 +00:00
8db3de6ede chore(actix-http): prepare release 3.6.0 2024-02-04 00:31:14 +00:00
2125aca2c5 Rustls v0.22 support (#3275) 2024-02-03 23:55:01 +00:00
b1eb57ac4f Update Cargo.toml (#3276) 2024-02-03 16:20:07 +00:00
ae7736f134 Implement From<&HeaderMap> for http::HeaderMap (#3230)
* Add From impl for header map references

* Add From impl for header map references

* Remove Into<HeaderMap> via http::HeaderMap

* fix changelog

---------

Co-authored-by: SleeplessOne1917 <insomnia-void@protonmail.com>
Co-authored-by: Rob Ede <robjtede@icloud.com>
2024-02-01 12:52:35 +00:00
c1f88f718b build(deps): bump codecov/codecov-action from 3.1.4 to 4.0.0 (#3272)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Rob Ede <robjtede@icloud.com>
2024-02-01 07:34:23 +00:00
7a76ba7340 build(deps): bump taiki-e/install-action from 2.24.1 to 2.26.8 (#3271)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-01 07:34:11 +00:00
8e458b34b7 chore: remove set -e 2024-02-01 06:33:58 +00:00
e89c881624 ci: use cargo-ci-cache-clean 2024-02-01 06:27:22 +00:00
5246d24aba ci: force openssl version 3.2.1 2024-02-01 06:01:28 +00:00
643a80bff2 ci: workaround half crate msrv 2024-02-01 05:41:28 +00:00
891ab083c6 actix-http: Bump h2 to fix a resource exhaustion vulnerability (#3262)
Co-authored-by: Rob Ede <robjtede@icloud.com>
2024-01-24 14:17:42 +00:00
a7375b6876 ci: faster cargo-public-api install (#3255) 2024-01-22 02:19:19 +00:00
ea8cd6e976 build(deps): bump taiki-e/install-action from 2.25.1 to 2.25.9 (#3252)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-22 01:06:55 +00:00
d453b15ddd docs: mention result is wrapped in Data in data_factory() docs (#3251) 2024-01-18 12:32:27 +00:00
2915bb7d90 chore: fix typos (#3248) 2024-01-16 11:29:06 +00:00
e442b00c8c build(deps): bump taiki-e/install-action from 2.24.1 to 2.25.1 (#3246)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-15 01:24:48 +00:00
ba53c4f875 build(deps): bump actions-rust-lang/setup-rust-toolchain from 1.6.0 to 1.8.0 (#3247)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-15 01:24:21 +00:00
08a9c66568 docs(files: update readme from crate docs 2024-01-10 04:03:29 +00:00
83be07d77d chore(actix-files): prepare release 0.6.5 2024-01-10 04:01:14 +00:00
33da480709 format project 2024-01-10 04:00:20 +00:00
fcfc727295 actix-files: fix handling linebreaks in filenames (#3237)
Co-authored-by: Rob Ede <robjtede@icloud.com>
2024-01-10 03:56:15 +00:00
ac04d80d8e docs: better docs for peer_addr methods 2024-01-08 15:17:40 +00:00
d2bd549eec build(deps): bump taiki-e/install-action from 2.23.7 to 2.24.1 (#3239)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.23.7 to 2.24.1.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.23.7...v2.24.1)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-08 01:25:54 +00:00
46dde69d50 chore(actix-files): prepare release 0.6.4 2024-01-06 10:19:15 +00:00
febba786fa actix-files: Properly handle newlines in file names (#3235) 2024-01-06 10:11:40 +00:00
561cc440b2 build(deps): bump taiki-e/install-action from 2.23.0 to 2.23.7 (#3232)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.23.0 to 2.23.7.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.23.0...v2.23.7)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-01 14:10:13 +00:00
ccb90dd5a1 docs: update changelog 2023-12-25 02:36:17 +00:00
1c88af50c0 docs: fix changelog 2023-12-25 02:35:22 +00:00
f4f459d420 chore(actix-http): prepare release 3.5.1 2023-12-25 02:30:14 +00:00
d14e98b62b prevent hang when compressing Sized(0) bodies
fixes #3229
2023-12-25 02:27:51 +00:00
f4851b3914 chore(actix-router): prepare release 0.5.2 2023-12-24 16:47:58 +00:00
68597b5426 build(deps): bump taiki-e/install-action from 2.22.0 to 2.23.0 (#3228)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.22.0 to 2.23.0.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.22.0...v2.23.0)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-23 19:54:02 +00:00
9dc3ad754e chore(actix-web): prepare release 4.4.1 2023-12-23 19:19:10 +00:00
17060ed993 chore(awc): prepare release 3.3.0 2023-12-23 19:18:29 +00:00
0d9ca4d939 chore(actix-http): prepare release 3.5.0 2023-12-23 19:17:56 +00:00
ff2904ee78 ci: prevent cargo-cache install failing MSRV builds 2023-12-23 19:13:11 +00:00
fdef224a06 docs: document internal Path fields 2023-12-23 18:49:17 +00:00
ede0201aa4 docs: fix derive readme version 2023-12-16 10:42:16 +00:00
271edafd4d docs: add router readme 2023-12-16 10:37:19 +00:00
5e5e5d8315 chore: remove allow(uninlined_format_args) 2023-12-16 10:33:00 +00:00
c7a0af31d3 docs: doc and metadata tweaks 2023-12-16 10:33:00 +00:00
eefe8b0733 Implement From<HeaderMap> for http::HeaderMap (#3222)
* Implement From<HeaderMap> for http::HeaderMap

* Update changelog

* Apply clippy fix

* doc tweak

---------

Co-authored-by: SleeplessOne1917 <insomnia-void@protonmail.com>
Co-authored-by: Rob Ede <robjtede@icloud.com>
2023-12-16 10:08:45 +00:00
1114a51b22 build(deps): bump taiki-e/install-action from 2.21.26 to 2.22.0 (#3219)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.21.26 to 2.22.0.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.21.26...v2.22.0)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-11 01:11:53 +00:00
0a312037ea Corrected a typo in mod.rs (#3218) 2023-12-10 15:53:05 +00:00
37d304b0f2 build(deps): bump taiki-e/install-action from 2.21.19 to 2.21.26 (#3210)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.21.19 to 2.21.26.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.21.19...v2.21.26)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-04 01:20:11 +00:00
039f8fb193 build(deps): bump JamesIves/github-pages-deploy-action from 4.4.3 to 4.5.0 (#3211)
build(deps): bump JamesIves/github-pages-deploy-action

Bumps [JamesIves/github-pages-deploy-action](https://github.com/jamesives/github-pages-deploy-action) from 4.4.3 to 4.5.0.
- [Release notes](https://github.com/jamesives/github-pages-deploy-action/releases)
- [Commits](https://github.com/jamesives/github-pages-deploy-action/compare/v4.4.3...v4.5.0)

---
updated-dependencies:
- dependency-name: JamesIves/github-pages-deploy-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-04 01:03:29 +00:00
929ceb5eb5 build(deps): bump actions-rust-lang/setup-rust-toolchain from 1.5.0 to 1.6.0 (#3212)
build(deps): bump actions-rust-lang/setup-rust-toolchain

Bumps [actions-rust-lang/setup-rust-toolchain](https://github.com/actions-rust-lang/setup-rust-toolchain) from 1.5.0 to 1.6.0.
- [Release notes](https://github.com/actions-rust-lang/setup-rust-toolchain/releases)
- [Changelog](https://github.com/actions-rust-lang/setup-rust-toolchain/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions-rust-lang/setup-rust-toolchain/compare/v1.5.0...v1.6.0)

---
updated-dependencies:
- dependency-name: actions-rust-lang/setup-rust-toolchain
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-04 01:02:25 +00:00
e95c8fe5a6 build(deps): bump taiki-e/install-action from 2.21.17 to 2.21.19 (#3205)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.21.17 to 2.21.19.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.21.17...v2.21.19)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-27 02:54:42 +00:00
2fe5189954 Do not encode zero-sized response bodies (#3199)
* Do not encode zero-sized response bodies

* Test empty response remains empty after compression
2023-11-26 20:57:19 +00:00
4accfab196 build(deps): bump taiki-e/install-action from 2.21.11 to 2.21.17 (#3195)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.21.11 to 2.21.17.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.21.11...v2.21.17)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-20 00:29:35 +00:00
c0615f28ed Make compression middleware prefer brotli over zstd over gzip (#3189)
* AcceptEncoding.preference() prefers brotli > zstd > gzip

* AcceptEncoding.{ranked,negotiate}() prefers brotli > zstd > gzip

* changelog entry

* use browser-realistic encoding tests

* fix choosing identity when q=0

---------

Co-authored-by: Rob Ede <robjtede@icloud.com>
2023-11-19 18:54:08 +00:00
9d1f75d349 fix: content type required flag (#3168)
* fix: content type required flag

* clarify comments for invalid json mime type

* remove pr reference

---------

Co-authored-by: Rob Ede <robjtede@icloud.com>
2023-11-19 11:22:55 +00:00
e50bceb914 build(deps): bump taiki-e/install-action from 2.21.7 to 2.21.11 (#3185)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.21.7 to 2.21.11.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.21.7...v2.21.11)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-13 02:00:08 +00:00
f5655721aa ci: rename lint workflow 2023-11-10 14:06:38 +00:00
989548e36a chore: remove git from repo URLs 2023-11-10 14:06:38 +00:00
7d2349afb9 build(deps): bump taiki-e/install-action from 2.21.3 to 2.21.7 (#3183)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.21.3 to 2.21.7.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.21.3...v2.21.7)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-06 02:17:07 +00:00
b78f6da05f build(deps): update zstd requirement from 0.12 to 0.13 (#3165)
* build(deps): update zstd requirement from 0.12 to 0.13

Updates the requirements on [zstd](https://github.com/gyscos/zstd-rs) to permit the latest version.
- [Release notes](https://github.com/gyscos/zstd-rs/releases)
- [Commits](https://github.com/gyscos/zstd-rs/compare/v0.12.0...v0.13.0)

---
updated-dependencies:
- dependency-name: zstd
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

* chore: update changelogs

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Rob Ede <robjtede@icloud.com>
2023-10-30 01:18:45 +00:00
3b8d4de0e0 build(deps): bump taiki-e/install-action from 2.20.14 to 2.21.3 (#3179)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.20.14 to 2.21.3.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.20.14...v2.21.3)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-30 01:12:42 +00:00
40196f16be build(deps): bump taiki-e/cache-cargo-install-action from 1.2.2 to 1.3.0 (#3167)
Bumps [taiki-e/cache-cargo-install-action](https://github.com/taiki-e/cache-cargo-install-action) from 1.2.2 to 1.3.0.
- [Release notes](https://github.com/taiki-e/cache-cargo-install-action/releases)
- [Changelog](https://github.com/taiki-e/cache-cargo-install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/cache-cargo-install-action/compare/v1.2.2...v1.3.0)

---
updated-dependencies:
- dependency-name: taiki-e/cache-cargo-install-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-30 00:05:50 +00:00
32ddf972c6 docs: add guarded-listings example 2023-10-30 00:03:22 +00:00
ce18f35e03 docs: improve HttpServer docs on worker / bind relationship wrt factory instantiations 2023-10-29 18:48:03 +00:00
d3d0208cbd chore: fmt workflows 2023-10-29 01:56:10 +00:00
9e51116da2 chore: remove unusable re-export 2023-10-29 01:53:03 +00:00
3193b81a3e build(deps): bump taiki-e/install-action from 2.20.2 to 2.20.14 (#3173)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.20.2 to 2.20.14.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.20.2...v2.20.14)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-23 01:21:06 +00:00
3acdda48e0 ci: reduce dependabot rate for Cargo updater 2023-10-13 17:41:25 +02:00
935d36c441 build(deps): bump taiki-e/install-action from 2.20.1 to 2.20.2 (#3163)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.20.1 to 2.20.2.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.20.1...v2.20.2)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-12 08:41:10 +00:00
05b4c4964f update handler failure mode docs 2023-10-11 16:07:18 +02:00
fba766b4be build(deps): bump taiki-e/install-action from 2.19.4 to 2.20.1 (#3160)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.19.4 to 2.20.1.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.19.4...v2.20.1)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-09 01:48:46 +00:00
76a0385f94 build(deps): bump taiki-e/install-action from 2.19.3 to 2.19.4 (#3159)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-06 02:51:36 +01:00
f1c9b93b87 build(deps): bump taiki-e/install-action from 2.19.2 to 2.19.3 (#3156)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.19.2 to 2.19.3.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.19.2...v2.19.3)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-03 09:45:32 +00:00
55ddded315 build(deps): bump taiki-e/install-action from 2.19.1 to 2.19.2 (#3154)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.19.1 to 2.19.2.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.19.1...v2.19.2)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-02 00:43:19 +00:00
2cfe257fc2 build(deps): bump taiki-e/install-action from 2.18.17 to 2.19.1 (#3151)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.18.17 to 2.19.1.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.18.17...v2.19.1)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-29 01:58:58 +00:00
ccabcd83c0 build(deps): bump taiki-e/install-action from 2.18.16 to 2.18.17 (#3149)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.18.16 to 2.18.17.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.18.16...v2.18.17)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-27 01:25:32 +00:00
13fed45bfa build(deps): bump taiki-e/install-action from 2.18.14 to 2.18.16 (#3144)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.18.14 to 2.18.16.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.18.14...v2.18.16)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-25 01:28:45 +00:00
8bd4b36ffe build(deps): bump taiki-e/install-action from 2.18.13 to 2.18.14 (#3142)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.18.13 to 2.18.14.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.18.13...v2.18.14)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-22 04:36:18 +00:00
801a51b312 build(deps): bump taiki-e/cache-cargo-install-action from 1.2.1 to 1.2.2 (#3139)
Bumps [taiki-e/cache-cargo-install-action](https://github.com/taiki-e/cache-cargo-install-action) from 1.2.1 to 1.2.2.
- [Release notes](https://github.com/taiki-e/cache-cargo-install-action/releases)
- [Changelog](https://github.com/taiki-e/cache-cargo-install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/cache-cargo-install-action/compare/v1.2.1...v1.2.2)

---
updated-dependencies:
- dependency-name: taiki-e/cache-cargo-install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-18 01:17:47 +00:00
b28e0fff4b build(deps): bump taiki-e/install-action from 2.18.9 to 2.18.13 (#3138)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.18.9 to 2.18.13.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.18.9...v2.18.13)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-18 01:15:19 +00:00
043bc88f73 docs: add note about rt::spawn compat with tokio::main 2023-09-15 22:20:48 +01:00
e1c48dba26 build(deps): bump taiki-e/install-action from 2.13.4 to 2.18.9 (#3133)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.13.4 to 2.18.9.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/v2.13.4...v2.18.9)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-13 01:06:53 +00:00
835a57afc6 build(deps): bump actions/checkout from 3 to 4 (#3130)
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-12 04:44:47 +00:00
81ac30f3df ci: overspecify actions versions 2023-09-12 05:24:55 +01:00
d50eccb3f7 ci: workaround anstyle msrv 2023-09-12 05:16:41 +01:00
a7983351be docs: fix Data doc 2023-09-12 04:45:36 +01:00
215a52f565 chore: avoid single char error bindings 2023-09-03 19:09:42 +01:00
d445742974 Update trust-dns-resolver requirement from 0.22 to 0.23 (#3121)
* Update trust-dns-resolver requirement from 0.22 to 0.23

Updates the requirements on [trust-dns-resolver](https://github.com/bluejekyll/trust-dns) to permit the latest version.
- [Release notes](https://github.com/bluejekyll/trust-dns/releases)
- [Changelog](https://github.com/bluejekyll/trust-dns/blob/main/CHANGELOG.md)
- [Commits](https://github.com/bluejekyll/trust-dns/compare/v0.22.0...v0.23.0)

---
updated-dependencies:
- dependency-name: trust-dns-resolver
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

* fixup post-upgrade

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Rob Ede <robjtede@icloud.com>
2023-09-03 04:40:41 +00:00
111 changed files with 1557 additions and 586 deletions

View File

@ -1,6 +1,6 @@
[alias]
lint = "clippy --workspace --tests --examples --bins -- -Dclippy::todo"
lint-all = "clippy --workspace --all-features --tests --examples --bins -- -Dclippy::todo"
lint = "clippy --workspace --all-targets -- -Dclippy::todo"
lint-all = "clippy --workspace --all-features --all-targets -- -Dclippy::todo"
# lib checking
ci-check-min = "hack --workspace check --no-default-features"

View File

@ -1,12 +1,10 @@
version: 2
updates:
- package-ecosystem: "cargo"
directory: "/"
- package-ecosystem: cargo
directory: /
schedule:
interval: "monthly"
open-pull-requests-limit: 10
- package-ecosystem: "github-actions"
directory: "/"
interval: weekly
- package-ecosystem: github-actions
directory: /
schedule:
interval: "monthly"
open-pull-requests-limit: 10
interval: weekly

View File

@ -5,7 +5,7 @@ on:
branches: [master]
permissions:
contents: read # to fetch code (actions/checkout)
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@ -16,7 +16,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Install Rust
run: |

View File

@ -28,24 +28,26 @@ jobs:
runs-on: ${{ matrix.target.os }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Install OpenSSL
if: matrix.target.os == 'windows-latest'
run: choco install openssl -y --forcex64 --no-progress
- name: Set OpenSSL dir in env
if: matrix.target.os == 'windows-latest'
shell: bash
run: |
echo 'OPENSSL_DIR=C:\Program Files\OpenSSL-Win64' | Out-File -FilePath $env:GITHUB_ENV -Append
echo 'OPENSSL_DIR=C:\Program Files\OpenSSL' | Out-File -FilePath $env:GITHUB_ENV -Append
set -e
choco install openssl --version=1.1.1.2100 -y --no-progress
echo 'OPENSSL_DIR=C:\Program Files\OpenSSL' >> $GITHUB_ENV
echo "RUSTFLAGS=-C target-feature=+crt-static" >> $GITHUB_ENV
- name: Install Rust (${{ matrix.version.name }})
uses: actions-rust-lang/setup-rust-toolchain@v1
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
with:
toolchain: ${{ matrix.version.version }}
- name: Install cargo-hack
uses: taiki-e/install-action@cargo-hack
- name: Install cargo-hack and cargo-ci-cache-clean
uses: taiki-e/install-action@v2.26.8
with:
tool: cargo-hack,cargo-ci-cache-clean
- name: check minimal
run: cargo ci-check-min
@ -55,10 +57,12 @@ jobs:
- name: tests
timeout-minutes: 60
shell: bash
run: |
set -e
cargo test --lib --tests -p=actix-router --all-features
cargo test --lib --tests -p=actix-http --all-features
cargo test --lib --tests -p=actix-web --features=rustls-0_20,rustls-0_21,openssl -- --skip=test_reading_deflate_encoding_large_random_rustls
cargo test --lib --tests -p=actix-web --features=rustls-0_20,rustls-0_21,rustls-0_22,openssl -- --skip=test_reading_deflate_encoding_large_random_rustls
cargo test --lib --tests -p=actix-web-codegen --all-features
cargo test --lib --tests -p=awc --all-features
cargo test --lib --tests -p=actix-http-test --all-features
@ -67,23 +71,23 @@ jobs:
cargo test --lib --tests -p=actix-multipart --all-features
cargo test --lib --tests -p=actix-web-actors --all-features
- name: Clear the cargo caches
run: |
cargo install cargo-cache --version 0.8.3 --no-default-features --features ci-autoclean
cargo-cache
- name: CI cache clean
run: cargo-ci-cache-clean
ci_feature_powerset_check:
name: Verify Feature Combinations
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
- name: Install cargo-hack
uses: taiki-e/install-action@cargo-hack
uses: taiki-e/install-action@v2.26.8
with:
tool: cargo-hack
- name: check feature combinations
run: cargo ci-check-all-feature-powerset
@ -96,13 +100,15 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
- name: Install nextest
uses: taiki-e/install-action@nextest
uses: taiki-e/install-action@v2.26.8
with:
tool: nextest
- name: Test with cargo-nextest
run: cargo nextest run

View File

@ -33,30 +33,35 @@ jobs:
runs-on: ${{ matrix.target.os }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Install OpenSSL
if: matrix.target.os == 'windows-latest'
run: choco install openssl -y --forcex64 --no-progress
- name: Set OpenSSL dir in env
if: matrix.target.os == 'windows-latest'
shell: bash
run: |
echo 'OPENSSL_DIR=C:\Program Files\OpenSSL-Win64' | Out-File -FilePath $env:GITHUB_ENV -Append
echo 'OPENSSL_DIR=C:\Program Files\OpenSSL' | Out-File -FilePath $env:GITHUB_ENV -Append
set -e
choco install openssl --version=1.1.1.2100 -y --no-progress
echo 'OPENSSL_DIR=C:\Program Files\OpenSSL' >> $GITHUB_ENV
echo "RUSTFLAGS=-C target-feature=+crt-static" >> $GITHUB_ENV
- name: Install Rust (${{ matrix.version.name }})
uses: actions-rust-lang/setup-rust-toolchain@v1
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
with:
toolchain: ${{ matrix.version.version }}
- name: Install cargo-hack
uses: taiki-e/install-action@cargo-hack
- name: Install cargo-hack and cargo-ci-cache-clean
uses: taiki-e/install-action@v2.26.8
with:
tool: cargo-hack,cargo-ci-cache-clean
- name: workaround MSRV issues
if: matrix.version.name != 'stable'
if: matrix.version.name == 'msrv'
run: |
cargo update -p=ciborium --precise=0.2.1
cargo update -p=ciborium-ll --precise=0.2.1
cargo update -p=clap --precise=4.3.24
cargo update -p=clap_lex --precise=0.5.0
cargo update -p=anstyle --precise=1.0.2
- name: check minimal
run: cargo ci-check-min
@ -66,10 +71,12 @@ jobs:
- name: tests
timeout-minutes: 60
shell: bash
run: |
set -e
cargo test --lib --tests -p=actix-router --all-features
cargo test --lib --tests -p=actix-http --all-features
cargo test --lib --tests -p=actix-web --features=rustls-0_20,rustls-0_21,openssl -- --skip=test_reading_deflate_encoding_large_random_rustls
cargo test --lib --tests -p=actix-web --features=rustls-0_20,rustls-0_21,rustls-0_22,openssl -- --skip=test_reading_deflate_encoding_large_random_rustls
cargo test --lib --tests -p=actix-web-codegen --all-features
cargo test --lib --tests -p=awc --all-features
cargo test --lib --tests -p=actix-http-test --all-features
@ -78,20 +85,19 @@ jobs:
cargo test --lib --tests -p=actix-multipart --all-features
cargo test --lib --tests -p=actix-web-actors --all-features
- name: Clear the cargo caches
run: |
cargo install cargo-cache --version 0.8.3 --no-default-features --features ci-autoclean
cargo-cache
- name: CI cache clean
run: cargo-ci-cache-clean
io-uring:
name: io-uring tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with: { toolchain: nightly }
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
with:
toolchain: nightly
- name: tests (io-uring)
timeout-minutes: 60
@ -102,11 +108,12 @@ jobs:
name: doc tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Install Rust (nightly)
uses: actions-rust-lang/setup-rust-toolchain@v1
with: { toolchain: nightly }
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
with:
toolchain: nightly
- name: doc tests
run: cargo ci-doctest

View File

@ -1,75 +0,0 @@
name: Lint
on:
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: read # to fetch code (actions/checkout)
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
fmt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: nightly
components: rustfmt
- run: cargo fmt --all -- --check
clippy:
permissions:
checks: write # to add clippy checks to PR diffs
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions-rust-lang/setup-rust-toolchain@v1
with: { components: clippy }
- uses: giraffate/clippy-action@v1
with:
reporter: 'github-pr-check'
github_token: ${{ secrets.GITHUB_TOKEN }}
clippy_flags: --workspace --all-features --tests --examples --bins -- -Dclippy::todo -Aunknown_lints
lint-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions-rust-lang/setup-rust-toolchain@v1
with: { components: rust-docs }
- name: Check for broken intra-doc links
env: { RUSTDOCFLAGS: "-D warnings" }
run: cargo doc --no-deps --all-features --workspace
public-api-diff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.base_ref }}
- uses: actions/checkout@v3
- uses: actions-rust-lang/setup-rust-toolchain@v1
with: { toolchain: nightly-2023-08-25 }
- uses: taiki-e/cache-cargo-install-action@v1
with: { tool: cargo-public-api }
- name: generate API diff
run: |
for f in $(find -mindepth 2 -maxdepth 2 -name Cargo.toml); do
cargo public-api --manifest-path "$f" diff ${{ github.event.pull_request.base.sha }}..${{ github.sha }}
done

View File

@ -15,14 +15,15 @@ jobs:
coverage:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1.5.0
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
with:
components: llvm-tools-preview
- name: Install cargo-llvm-cov
uses: taiki-e/install-action@v2.13.4
uses: taiki-e/install-action@v2.26.8
with:
tool: cargo-llvm-cov
@ -30,7 +31,9 @@ jobs:
run: cargo llvm-cov --workspace --all-features --codecov --output-path codecov.json
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3.1.4
uses: codecov/codecov-action@v4.0.0
with:
files: codecov.json
fail_ci_if_error: true
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}

93
.github/workflows/lint.yml vendored Normal file
View File

@ -0,0 +1,93 @@
name: Lint
on:
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
fmt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust (nightly)
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
with:
toolchain: nightly
components: rustfmt
- name: Check with Rustfmt
run: cargo fmt --all -- --check
clippy:
permissions:
contents: read
checks: write # to add clippy checks to PR diffs
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
with:
components: clippy
- name: Check with Clippy
uses: giraffate/clippy-action@v1.0.1
with:
reporter: github-pr-check
github_token: ${{ secrets.GITHUB_TOKEN }}
clippy_flags: >-
--workspace --all-features --tests --examples --bins --
-A unknown_lints -D clippy::todo -D clippy::dbg_macro
lint-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust (nightly)
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
with:
toolchain: nightly
components: rust-docs
- name: Check for broken intra-doc links
env:
RUSTDOCFLAGS: -D warnings
run: cargo +nightly doc --no-deps --workspace --all-features
public-api-diff:
runs-on: ubuntu-latest
steps:
- name: Checkout main branch
uses: actions/checkout@v4
with:
ref: ${{ github.base_ref }}
- name: Checkout PR branch
uses: actions/checkout@v4
- name: Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
with:
toolchain: nightly-2023-08-25
- name: Install cargo-public-api
uses: taiki-e/install-action@v2.26.8
with:
tool: cargo-public-api
- name: Generate API diff
run: |
for f in $(find -mindepth 2 -maxdepth 2 -name Cargo.toml); do
cargo public-api --manifest-path "$f" diff ${{ github.event.pull_request.base.sha }}..${{ github.sha }}
done

View File

@ -5,7 +5,7 @@ on:
branches: [master]
permissions:
contents: read # to fetch code (actions/checkout)
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@ -14,14 +14,17 @@ concurrency:
jobs:
build:
permissions:
contents: write # to push changes in repo (jamesives/github-pages-deploy-action)
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly
- name: Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
with:
toolchain: nightly
- name: Build Docs
run: cargo +nightly doc --no-deps --workspace --all-features
@ -32,7 +35,7 @@ jobs:
run: echo '<meta http-equiv="refresh" content="0;url=actix_web/index.html">' > target/doc/index.html
- name: Deploy to GitHub Pages
uses: JamesIves/github-pages-deploy-action@v4.4.3
uses: JamesIves/github-pages-deploy-action@v4.5.0
with:
folder: target/doc
single-commit: true

View File

@ -1,5 +1,5 @@
overrides:
- files: '*.md'
- files: "*.md"
options:
printWidth: 9999
proseWrap: never

View File

@ -2,6 +2,13 @@
## Unreleased
## 0.6.5
- Fix handling of special characters in filenames.
## 0.6.4
- Fix handling of newlines in filenames.
- Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency.
## 0.6.3

View File

@ -1,6 +1,6 @@
[package]
name = "actix-files"
version = "0.6.3"
version = "0.6.5"
authors = [
"Nikolay Kim <fafhrd91@gmail.com>",
"Rob Ede <robjtede@icloud.com>",
@ -47,4 +47,5 @@ actix-server = { version = "2.2", optional = true } # ensure matching tokio-urin
actix-rt = "2.7"
actix-test = "0.1"
actix-web = "4"
env_logger = "0.10"
tempfile = "3.2"

View File

@ -1,18 +1,32 @@
# actix-files
# `actix-files`
> Static file serving for Actix Web
<!-- prettier-ignore-start -->
[![crates.io](https://img.shields.io/crates/v/actix-files?label=latest)](https://crates.io/crates/actix-files)
[![Documentation](https://docs.rs/actix-files/badge.svg?version=0.6.3)](https://docs.rs/actix-files/0.6.3)
[![Documentation](https://docs.rs/actix-files/badge.svg?version=0.6.5)](https://docs.rs/actix-files/0.6.5)
![Version](https://img.shields.io/badge/rustc-1.68+-ab6000.svg)
![License](https://img.shields.io/crates/l/actix-files.svg)
<br />
[![dependency status](https://deps.rs/crate/actix-files/0.6.3/status.svg)](https://deps.rs/crate/actix-files/0.6.3)
[![dependency status](https://deps.rs/crate/actix-files/0.6.5/status.svg)](https://deps.rs/crate/actix-files/0.6.5)
[![Download](https://img.shields.io/crates/d/actix-files.svg)](https://crates.io/crates/actix-files)
[![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x)
## Documentation & Resources
<!-- prettier-ignore-end -->
- [API Documentation](https://docs.rs/actix-files)
- [Example Project](https://github.com/actix/examples/tree/master/basics/static-files)
- Minimum Supported Rust Version (MSRV): 1.68
<!-- cargo-rdme start -->
Static file serving for Actix Web.
Provides a non-blocking service for serving static files from disk.
## Examples
```rust
use actix_web::App;
use actix_files::Files;
let app = App::new()
.service(Files::new("/static", ".").prefer_utf8(true));
```
<!-- cargo-rdme end -->

View File

@ -0,0 +1,33 @@
use actix_files::Files;
use actix_web::{get, guard, middleware, App, HttpServer, Responder};
const EXAMPLES_DIR: &str = concat![env!("CARGO_MANIFEST_DIR"), "/examples"];
#[get("/")]
async fn index() -> impl Responder {
"Hello world!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
log::info!("starting HTTP server at http://localhost:8080");
HttpServer::new(|| {
App::new()
.service(index)
.service(
Files::new("/assets", EXAMPLES_DIR)
.show_files_listing()
.guard(guard::Header("show-listing", "?1")),
)
.service(Files::new("/assets", EXAMPLES_DIR))
.wrap(middleware::Compress::default())
.wrap(middleware::Logger::default())
})
.bind(("127.0.0.1", 8080))?
.workers(2)
.run()
.await
}

View File

@ -235,7 +235,7 @@ impl Files {
/// request starts being handled by the file service, it will not be able to back-out and try
/// the next service, you will simply get a 404 (or 405) error response.
///
/// To allow `POST` requests to retrieve files, see [`Files::use_guards`].
/// To allow `POST` requests to retrieve files, see [`Files::method_guard()`].
///
/// # Examples
/// ```

View File

@ -13,7 +13,6 @@
#![deny(rust_2018_idioms, nonstandard_style)]
#![warn(future_incompatible, missing_docs, missing_debug_implementations)]
#![allow(clippy::uninlined_format_args)]
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
@ -569,6 +568,30 @@ mod tests {
assert_eq!(bytes, data);
}
#[cfg(not(target_os = "windows"))]
#[actix_rt::test]
async fn test_static_files_with_special_characters() {
// Create the file we want to test against ad-hoc. We can't check it in as otherwise
// Windows can't even checkout this repository.
let temp_dir = tempfile::tempdir().unwrap();
let file_with_newlines = temp_dir.path().join("test\n\x0B\x0C\rnewline.text");
fs::write(&file_with_newlines, "Look at my newlines").unwrap();
let srv = test::init_service(
App::new().service(Files::new("/", temp_dir.path()).index_file("Cargo.toml")),
)
.await;
let request = TestRequest::get()
.uri("/test%0A%0B%0C%0Dnewline.text")
.to_request();
let response = test::call_service(&srv, request).await;
assert_eq!(response.status(), StatusCode::OK);
let bytes = test::read_body(response).await;
let data = web::Bytes::from(fs::read(file_with_newlines).unwrap());
assert_eq!(bytes, data);
}
#[actix_rt::test]
async fn test_files_not_allowed() {
let srv = test::init_service(App::new().service(Files::new("/", "."))).await;
@ -841,9 +864,9 @@ mod tests {
#[actix_rt::test]
async fn test_percent_encoding_2() {
let tmpdir = tempfile::tempdir().unwrap();
let temp_dir = tempfile::tempdir().unwrap();
let filename = match cfg!(unix) {
true => "ض:?#[]{}<>()@!$&'`|*+,;= %20.test",
true => "ض:?#[]{}<>()@!$&'`|*+,;= %20\n.test",
false => "ض#[]{}()@!$&'`+,;= %20.test",
};
let filename_encoded = filename
@ -853,9 +876,9 @@ mod tests {
write!(&mut buf, "%{:02X}", c).unwrap();
buf
});
std::fs::File::create(tmpdir.path().join(filename)).unwrap();
std::fs::File::create(temp_dir.path().join(filename)).unwrap();
let srv = test::init_service(App::new().service(Files::new("", tmpdir.path()))).await;
let srv = test::init_service(App::new().service(Files::new("/", temp_dir.path()))).await;
let req = TestRequest::get()
.uri(&format!("/{}", filename_encoded))

View File

@ -24,7 +24,6 @@ use bitflags::bitflags;
use derive_more::{Deref, DerefMut};
use futures_core::future::LocalBoxFuture;
use mime::Mime;
use mime_guess::from_path;
use crate::{encoding::equiv_utf8_text, range::HttpRange};
@ -128,7 +127,7 @@ impl NamedFile {
}
};
let ct = from_path(&path).first_or_octet_stream();
let ct = mime_guess::from_path(&path).first_or_octet_stream();
let disposition = match ct.type_() {
mime::IMAGE | mime::TEXT | mime::AUDIO | mime::VIDEO => DispositionType::Inline,
@ -140,7 +139,13 @@ impl NamedFile {
_ => DispositionType::Attachment,
};
let mut parameters = vec![DispositionParam::Filename(String::from(filename.as_ref()))];
// replace special characters in filenames which could occur on some filesystems
let filename_s = filename
.replace('\n', "%0A") // \n line break
.replace('\x0B', "%0B") // \v vertical tab
.replace('\x0C', "%0C") // \f form feed
.replace('\r', "%0D"); // \r carriage return
let mut parameters = vec![DispositionParam::Filename(filename_s)];
if !filename.is_ascii() {
parameters.push(DispositionParam::FilenameExt(ExtendedValue {

View File

@ -2,6 +2,8 @@
## Unreleased
## 3.2.0
- Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency.
## 3.1.0

View File

@ -1,11 +1,11 @@
[package]
name = "actix-http-test"
version = "3.1.0"
version = "3.2.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Various helpers for Actix applications to use during testing"
keywords = ["http", "web", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
repository = "https://github.com/actix/actix-web"
categories = [
"network-programming",
"asynchronous",

View File

@ -1,16 +1,20 @@
# actix-http-test
# `actix-http-test`
> Various helpers for Actix applications to use during testing.
<!-- prettier-ignore-start -->
[![crates.io](https://img.shields.io/crates/v/actix-http-test?label=latest)](https://crates.io/crates/actix-http-test)
[![Documentation](https://docs.rs/actix-http-test/badge.svg?version=3.1.0)](https://docs.rs/actix-http-test/3.1.0)
[![Documentation](https://docs.rs/actix-http-test/badge.svg?version=3.2.0)](https://docs.rs/actix-http-test/3.2.0)
![Version](https://img.shields.io/badge/rustc-1.68+-ab6000.svg)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-http-test)
<br>
[![Dependency Status](https://deps.rs/crate/actix-http-test/3.1.0/status.svg)](https://deps.rs/crate/actix-http-test/3.1.0)
[![Dependency Status](https://deps.rs/crate/actix-http-test/3.2.0/status.svg)](https://deps.rs/crate/actix-http-test/3.2.0)
[![Download](https://img.shields.io/crates/d/actix-http-test.svg)](https://crates.io/crates/actix-http-test)
[![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x)
<!-- prettier-ignore-end -->
## Documentation & Resources
- [API Documentation](https://docs.rs/actix-http-test)

View File

@ -2,7 +2,6 @@
#![deny(rust_2018_idioms, nonstandard_style)]
#![warn(future_incompatible)]
#![allow(clippy::uninlined_format_args)]
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

View File

@ -2,6 +2,34 @@
## Unreleased
## 3.6.0
### Added
- Add `rustls-0_22` crate feature.
- Add `{h1::H1Service, h2::H2Service, HttpService}::rustls_0_22()` and `HttpService::rustls_0_22_with_config()` service constructors.
- Implement `From<&HeaderMap>` for `http::HeaderMap`.
## 3.5.1
### Fixed
- Prevent hang when returning zero-sized response bodies through compression layer.
## 3.5.0
### Added
- Implement `From<HeaderMap>` for `http::HeaderMap`.
### Changed
- Updated `zstd` dependency to `0.13`.
### Fixed
- Prevent compression of zero-sized response bodies.
## 3.4.0
### Added

View File

@ -1,14 +1,14 @@
[package]
name = "actix-http"
version = "3.4.0"
version = "3.6.0"
authors = [
"Nikolay Kim <fafhrd91@gmail.com>",
"Rob Ede <robjtede@icloud.com>",
]
description = "HTTP primitives for the Actix ecosystem"
description = "HTTP types and services for the Actix ecosystem"
keywords = ["actix", "http", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
repository = "https://github.com/actix/actix-web"
categories = [
"network-programming",
"asynchronous",
@ -20,8 +20,18 @@ edition.workspace = true
rust-version.workspace = true
[package.metadata.docs.rs]
# features that docs.rs will build with
features = ["http2", "ws", "openssl", "rustls-0_20", "rustls-0_21", "compress-brotli", "compress-gzip", "compress-zstd"]
rustdoc-args = ["--cfg", "docsrs"]
features = [
"http2",
"ws",
"openssl",
"rustls-0_20",
"rustls-0_21",
"rustls-0_22",
"compress-brotli",
"compress-gzip",
"compress-zstd",
]
[lib]
name = "actix_http"
@ -53,6 +63,9 @@ rustls-0_20 = ["actix-tls/accept", "actix-tls/rustls-0_20"]
# TLS via Rustls v0.21
rustls-0_21 = ["actix-tls/accept", "actix-tls/rustls-0_21"]
# TLS via Rustls v0.22
rustls-0_22 = ["actix-tls/accept", "actix-tls/rustls-0_22"]
# Compression codecs
compress-brotli = ["__compress", "brotli"]
compress-gzip = ["__compress", "flate2"]
@ -89,7 +102,7 @@ tokio-util = { version = "0.7", features = ["io", "codec"] }
tracing = { version = "0.1.30", default-features = false, features = ["log"] }
# http2
h2 = { version = "0.3.17", optional = true }
h2 = { version = "0.3.24", optional = true }
# websockets
local-channel = { version = "0.1", optional = true }
@ -98,17 +111,17 @@ rand = { version = "0.8", optional = true }
sha1 = { version = "0.10", optional = true }
# openssl/rustls
actix-tls = { version = "3.1", default-features = false, optional = true }
actix-tls = { version = "3.3", default-features = false, optional = true }
# compress-*
brotli = { version = "3.3.3", optional = true }
flate2 = { version = "1.0.13", optional = true }
zstd = { version = "0.12", optional = true }
zstd = { version = "0.13", optional = true }
[dev-dependencies]
actix-http-test = { version = "3", features = ["openssl"] }
actix-server = "2"
actix-tls = { version = "3.1", features = ["openssl"] }
actix-tls = { version = "3.3", features = ["openssl", "rustls-0_22-webpki-roots"] }
actix-web = "4"
async-stream = "0.3"
@ -117,24 +130,24 @@ env_logger = "0.10"
futures-util = { version = "0.3.17", default-features = false, features = ["alloc"] }
memchr = "2.4"
once_cell = "1.9"
rcgen = "0.11"
rcgen = "0.12"
regex = "1.3"
rustversion = "1"
rustls-pemfile = "1"
rustls-pemfile = "2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
static_assertions = "1"
tls-openssl = { package = "openssl", version = "0.10.55" }
tls-rustls_021 = { package = "rustls", version = "0.21" }
tls-rustls_022 = { package = "rustls", version = "0.22" }
tokio = { version = "1.24.2", features = ["net", "rt", "macros"] }
[[example]]
name = "ws"
required-features = ["ws", "rustls-0_21"]
required-features = ["ws", "rustls-0_22"]
[[example]]
name = "tls_rustls"
required-features = ["http2", "rustls-0_21"]
required-features = ["http2", "rustls-0_22"]
[[bench]]
name = "response-body-compression"

View File

@ -1,22 +1,26 @@
# actix-http
# `actix-http`
> HTTP primitives for the Actix ecosystem.
> HTTP types and services for the Actix ecosystem.
<!-- prettier-ignore-start -->
[![crates.io](https://img.shields.io/crates/v/actix-http?label=latest)](https://crates.io/crates/actix-http)
[![Documentation](https://docs.rs/actix-http/badge.svg?version=3.4.0)](https://docs.rs/actix-http/3.4.0)
[![Documentation](https://docs.rs/actix-http/badge.svg?version=3.6.0)](https://docs.rs/actix-http/3.6.0)
![Version](https://img.shields.io/badge/rustc-1.68+-ab6000.svg)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-http.svg)
<br />
[![dependency status](https://deps.rs/crate/actix-http/3.4.0/status.svg)](https://deps.rs/crate/actix-http/3.4.0)
[![dependency status](https://deps.rs/crate/actix-http/3.6.0/status.svg)](https://deps.rs/crate/actix-http/3.6.0)
[![Download](https://img.shields.io/crates/d/actix-http.svg)](https://crates.io/crates/actix-http)
[![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x)
<!-- prettier-ignore-end -->
## Documentation & Resources
- [API Documentation](https://docs.rs/actix-http)
- Minimum Supported Rust Version (MSRV): 1.68
## Example
## Examples
```rust
use std::{env, io};

View File

@ -1,5 +1,3 @@
#![allow(clippy::uninlined_format_args)]
use std::convert::Infallible;
use actix_http::{encoding::Encoder, ContentEncoding, Request, Response, StatusCode};

View File

@ -12,7 +12,7 @@
//! Protocol: HTTP/1.1
//! ```
extern crate tls_rustls_021 as rustls;
extern crate tls_rustls_022 as rustls;
use std::io;
@ -36,7 +36,7 @@ async fn main() -> io::Result<()> {
);
ok::<_, Error>(Response::ok().set_body(body))
})
.rustls_021(rustls_config())
.rustls_0_22(rustls_config())
})?
.run()
.await
@ -51,16 +51,18 @@ fn rustls_config() -> rustls::ServerConfig {
let key_file = &mut io::BufReader::new(key_file.as_bytes());
let cert_chain = rustls_pemfile::certs(cert_file)
.unwrap()
.into_iter()
.map(rustls::Certificate)
.collect();
let mut keys = rustls_pemfile::pkcs8_private_keys(key_file).unwrap();
.collect::<Result<Vec<_>, _>>()
.unwrap();
let mut keys = rustls_pemfile::pkcs8_private_keys(key_file)
.collect::<Result<Vec<_>, _>>()
.unwrap();
let mut config = rustls::ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth()
.with_single_cert(cert_chain, rustls::PrivateKey(keys.remove(0)))
.with_single_cert(
cert_chain,
rustls::pki_types::PrivateKeyDer::Pkcs8(keys.remove(0)),
)
.unwrap();
const H1_ALPN: &[u8] = b"http/1.1";

View File

@ -1,7 +1,7 @@
//! Sets up a WebSocket server over TCP and TLS.
//! Sends a heartbeat message every 4 seconds but does not respond to any incoming frames.
extern crate tls_rustls_021 as rustls;
extern crate tls_rustls_022 as rustls;
use std::{
io,
@ -30,7 +30,7 @@ async fn main() -> io::Result<()> {
.bind("tls", ("127.0.0.1", 8443), || {
HttpService::build()
.finish(handler)
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})?
.run()
.await
@ -85,7 +85,6 @@ impl Stream for Heartbeat {
fn tls_config() -> rustls::ServerConfig {
use std::io::BufReader;
use rustls::{Certificate, PrivateKey};
use rustls_pemfile::{certs, pkcs8_private_keys};
let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_owned()]).unwrap();
@ -95,17 +94,17 @@ fn tls_config() -> rustls::ServerConfig {
let cert_file = &mut BufReader::new(cert_file.as_bytes());
let key_file = &mut BufReader::new(key_file.as_bytes());
let cert_chain = certs(cert_file)
.unwrap()
.into_iter()
.map(Certificate)
.collect();
let mut keys = pkcs8_private_keys(key_file).unwrap();
let cert_chain = certs(cert_file).collect::<Result<Vec<_>, _>>().unwrap();
let mut keys = pkcs8_private_keys(key_file)
.collect::<Result<Vec<_>, _>>()
.unwrap();
let mut config = rustls::ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth()
.with_single_cert(cert_chain, PrivateKey(keys.remove(0)))
.with_single_cert(
cert_chain,
rustls::pki_types::PrivateKeyDer::Pkcs8(keys.remove(0)),
)
.unwrap();
config.alpn_protocols.push(b"http/1.1".to_vec());

View File

@ -191,7 +191,7 @@ impl ContentDecoder {
Ok(None)
}
}
Err(e) => Err(e),
Err(err) => Err(err),
},
#[cfg(feature = "compress-gzip")]
@ -205,7 +205,7 @@ impl ContentDecoder {
Ok(None)
}
}
Err(e) => Err(e),
Err(err) => Err(err),
},
#[cfg(feature = "compress-gzip")]
@ -218,7 +218,7 @@ impl ContentDecoder {
Ok(None)
}
}
Err(e) => Err(e),
Err(err) => Err(err),
},
#[cfg(feature = "compress-zstd")]
@ -231,7 +231,7 @@ impl ContentDecoder {
Ok(None)
}
}
Err(e) => Err(e),
Err(err) => Err(err),
},
}
}
@ -250,7 +250,7 @@ impl ContentDecoder {
Ok(None)
}
}
Err(e) => Err(e),
Err(err) => Err(err),
},
#[cfg(feature = "compress-gzip")]
@ -265,7 +265,7 @@ impl ContentDecoder {
Ok(None)
}
}
Err(e) => Err(e),
Err(err) => Err(err),
},
#[cfg(feature = "compress-gzip")]
@ -280,7 +280,7 @@ impl ContentDecoder {
Ok(None)
}
}
Err(e) => Err(e),
Err(err) => Err(err),
},
#[cfg(feature = "compress-zstd")]
@ -295,7 +295,7 @@ impl ContentDecoder {
Ok(None)
}
}
Err(e) => Err(e),
Err(err) => Err(err),
},
}
}

View File

@ -50,10 +50,21 @@ impl<B: MessageBody> Encoder<B> {
}
}
fn empty() -> Self {
Encoder {
body: EncoderBody::Full { body: Bytes::new() },
encoder: None,
fut: None,
eof: true,
}
}
pub fn response(encoding: ContentEncoding, head: &mut ResponseHead, body: B) -> Self {
// no need to compress an empty body
if matches!(body.size(), BodySize::None) {
return Self::none();
// no need to compress empty bodies
match body.size() {
BodySize::None => return Self::none(),
BodySize::Sized(0) => return Self::empty(),
_ => {}
}
let should_encode = !(head.headers().contains_key(&CONTENT_ENCODING)

View File

@ -532,7 +532,7 @@ impl Decoder for PayloadDecoder {
*state = match state.step(src, size, &mut buf) {
Poll::Pending => return Ok(None),
Poll::Ready(Ok(state)) => state,
Poll::Ready(Err(e)) => return Err(e),
Poll::Ready(Err(err)) => return Err(err),
};
if *state == ChunkedState::End {

View File

@ -153,7 +153,7 @@ mod openssl {
}
#[cfg(feature = "rustls-0_20")]
mod rustls_020 {
mod rustls_0_20 {
use std::io;
use actix_service::ServiceFactoryExt as _;
@ -214,7 +214,7 @@ mod rustls_020 {
}
#[cfg(feature = "rustls-0_21")]
mod rustls_021 {
mod rustls_0_21 {
use std::io;
use actix_service::ServiceFactoryExt as _;
@ -274,6 +274,67 @@ mod rustls_021 {
}
}
#[cfg(feature = "rustls-0_22")]
mod rustls_0_22 {
use std::io;
use actix_service::ServiceFactoryExt as _;
use actix_tls::accept::{
rustls_0_22::{reexports::ServerConfig, Acceptor, TlsStream},
TlsError,
};
use super::*;
impl<S, B, X, U> H1Service<TlsStream<TcpStream>, S, B, X, U>
where
S: ServiceFactory<Request, Config = ()>,
S::Future: 'static,
S::Error: Into<Response<BoxBody>>,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>>,
B: MessageBody,
X: ServiceFactory<Request, Config = (), Response = Request>,
X::Future: 'static,
X::Error: Into<Response<BoxBody>>,
X::InitError: fmt::Debug,
U: ServiceFactory<
(Request, Framed<TlsStream<TcpStream>, Codec>),
Config = (),
Response = (),
>,
U::Future: 'static,
U::Error: fmt::Display + Into<Response<BoxBody>>,
U::InitError: fmt::Debug,
{
/// Create Rustls v0.22 based service.
pub fn rustls_0_22(
self,
config: ServerConfig,
) -> impl ServiceFactory<
TcpStream,
Config = (),
Response = (),
Error = TlsError<io::Error, DispatchError>,
InitError = (),
> {
Acceptor::new(config)
.map_init_err(|_| {
unreachable!("TLS acceptor service factory does not error on init")
})
.map_err(TlsError::into_service_error)
.map(|io: TlsStream<TcpStream>| {
let peer_addr = io.get_ref().0.peer_addr().ok();
(io, peer_addr)
})
.and_then(self.map_err(TlsError::Service))
}
}
}
impl<T, S, B, X, U> H1Service<T, S, B, X, U>
where
S: ServiceFactory<Request, Config = ()>,

View File

@ -141,7 +141,7 @@ mod openssl {
}
#[cfg(feature = "rustls-0_20")]
mod rustls_020 {
mod rustls_0_20 {
use std::io;
use actix_service::ServiceFactoryExt as _;
@ -192,7 +192,7 @@ mod rustls_020 {
}
#[cfg(feature = "rustls-0_21")]
mod rustls_021 {
mod rustls_0_21 {
use std::io;
use actix_service::ServiceFactoryExt as _;
@ -242,6 +242,57 @@ mod rustls_021 {
}
}
#[cfg(feature = "rustls-0_22")]
mod rustls_0_22 {
use std::io;
use actix_service::ServiceFactoryExt as _;
use actix_tls::accept::{
rustls_0_22::{reexports::ServerConfig, Acceptor, TlsStream},
TlsError,
};
use super::*;
impl<S, B> H2Service<TlsStream<TcpStream>, S, B>
where
S: ServiceFactory<Request, Config = ()>,
S::Future: 'static,
S::Error: Into<Response<BoxBody>> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
{
/// Create Rustls v0.22 based service.
pub fn rustls_0_22(
self,
mut config: ServerConfig,
) -> impl ServiceFactory<
TcpStream,
Config = (),
Response = (),
Error = TlsError<io::Error, DispatchError>,
InitError = S::InitError,
> {
let mut protos = vec![b"h2".to_vec()];
protos.extend_from_slice(&config.alpn_protocols);
config.alpn_protocols = protos;
Acceptor::new(config)
.map_init_err(|_| {
unreachable!("TLS acceptor service factory does not error on init")
})
.map_err(TlsError::into_service_error)
.map(|io: TlsStream<TcpStream>| {
let peer_addr = io.get_ref().0.peer_addr().ok();
(io, peer_addr)
})
.and_then(self.map_err(TlsError::Service))
}
}
}
impl<T, S, B> ServiceFactory<(T, Option<net::SocketAddr>)> for H2Service<T, S, B>
where
T: AsyncRead + AsyncWrite + Unpin + 'static,

View File

@ -636,10 +636,24 @@ impl<'a> IntoIterator for &'a HeaderMap {
}
}
/// Convert `http::HeaderMap` to our `HeaderMap`.
/// Convert a `http::HeaderMap` to our `HeaderMap`.
impl From<http::HeaderMap> for HeaderMap {
fn from(mut map: http::HeaderMap) -> HeaderMap {
HeaderMap::from_drain(map.drain())
fn from(mut map: http::HeaderMap) -> Self {
Self::from_drain(map.drain())
}
}
/// Convert our `HeaderMap` to a `http::HeaderMap`.
impl From<HeaderMap> for http::HeaderMap {
fn from(map: HeaderMap) -> Self {
Self::from_iter(map)
}
}
/// Convert our `&HeaderMap` to a `http::HeaderMap`.
impl From<&HeaderMap> for http::HeaderMap {
fn from(map: &HeaderMap) -> Self {
map.to_owned().into()
}
}

View File

@ -1,6 +1,7 @@
//! HTTP primitives for the Actix ecosystem.
//! HTTP types and services for the Actix ecosystem.
//!
//! ## Crate Features
//!
//! | Feature | Functionality |
//! | ------------------- | ------------------------------------------- |
//! | `http2` | HTTP/2 support via [h2]. |
@ -21,8 +22,7 @@
#![allow(
clippy::type_complexity,
clippy::too_many_arguments,
clippy::borrow_interior_mutable_const,
clippy::uninlined_format_args
clippy::borrow_interior_mutable_const
)]
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
@ -58,7 +58,12 @@ pub mod ws;
#[allow(deprecated)]
pub use self::payload::PayloadStream;
#[cfg(any(feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21"))]
#[cfg(any(
feature = "openssl",
feature = "rustls-0_20",
feature = "rustls-0_21",
feature = "rustls-0_22",
))]
pub use self::service::TlsAcceptorConfig;
pub use self::{
builder::HttpServiceBuilder,

View File

@ -16,7 +16,10 @@ pub struct RequestHead {
pub uri: Uri,
pub version: Version,
pub headers: HeaderMap,
/// Will only be None when called in unit tests unless set manually.
pub peer_addr: Option<net::SocketAddr>,
flags: Flags,
}

View File

@ -173,7 +173,7 @@ impl<P> Request<P> {
/// Peer address is the directly connected peer's socket address. If a proxy is used in front of
/// the Actix Web server, then it would be address of this proxy.
///
/// Will only return None when called in unit tests.
/// Will only return None when called in unit tests unless set manually.
#[inline]
pub fn peer_addr(&self) -> Option<net::SocketAddr> {
self.head().peer_addr

View File

@ -93,7 +93,7 @@ impl ResponseBuilder {
Ok((key, value)) => {
parts.headers.insert(key, value);
}
Err(e) => self.err = Some(e.into()),
Err(err) => self.err = Some(err.into()),
};
}
@ -119,7 +119,7 @@ impl ResponseBuilder {
if let Some(parts) = self.inner() {
match header.try_into_pair() {
Ok((key, value)) => parts.headers.append(key, value),
Err(e) => self.err = Some(e.into()),
Err(err) => self.err = Some(err.into()),
};
}
@ -193,7 +193,7 @@ impl ResponseBuilder {
Ok(value) => {
parts.headers.insert(header::CONTENT_TYPE, value);
}
Err(e) => self.err = Some(e.into()),
Err(err) => self.err = Some(err.into()),
};
}
self

View File

@ -241,13 +241,23 @@ where
}
/// Configuration options used when accepting TLS connection.
#[cfg(any(feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21"))]
#[cfg(any(
feature = "openssl",
feature = "rustls-0_20",
feature = "rustls-0_21",
feature = "rustls-0_22",
))]
#[derive(Debug, Default)]
pub struct TlsAcceptorConfig {
pub(crate) handshake_timeout: Option<std::time::Duration>,
}
#[cfg(any(feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21"))]
#[cfg(any(
feature = "openssl",
feature = "rustls-0_20",
feature = "rustls-0_21",
feature = "rustls-0_22",
))]
impl TlsAcceptorConfig {
/// Set TLS handshake timeout duration.
pub fn handshake_timeout(self, dur: std::time::Duration) -> Self {
@ -353,12 +363,12 @@ mod openssl {
}
#[cfg(feature = "rustls-0_20")]
mod rustls_020 {
mod rustls_0_20 {
use std::io;
use actix_service::ServiceFactoryExt as _;
use actix_tls::accept::{
rustls::{reexports::ServerConfig, Acceptor, TlsStream},
rustls_0_20::{reexports::ServerConfig, Acceptor, TlsStream},
TlsError,
};
@ -389,7 +399,7 @@ mod rustls_020 {
U::Error: fmt::Display + Into<Response<BoxBody>>,
U::InitError: fmt::Debug,
{
/// Create Rustls based service.
/// Create Rustls v0.20 based service.
pub fn rustls(
self,
config: ServerConfig,
@ -403,7 +413,7 @@ mod rustls_020 {
self.rustls_with_config(config, TlsAcceptorConfig::default())
}
/// Create Rustls based service with custom TLS acceptor configuration.
/// Create Rustls v0.20 based service with custom TLS acceptor configuration.
pub fn rustls_with_config(
self,
mut config: ServerConfig,
@ -449,7 +459,7 @@ mod rustls_020 {
}
#[cfg(feature = "rustls-0_21")]
mod rustls_021 {
mod rustls_0_21 {
use std::io;
use actix_service::ServiceFactoryExt as _;
@ -485,7 +495,7 @@ mod rustls_021 {
U::Error: fmt::Display + Into<Response<BoxBody>>,
U::InitError: fmt::Debug,
{
/// Create Rustls based service.
/// Create Rustls v0.21 based service.
pub fn rustls_021(
self,
config: ServerConfig,
@ -499,7 +509,7 @@ mod rustls_021 {
self.rustls_021_with_config(config, TlsAcceptorConfig::default())
}
/// Create Rustls based service with custom TLS acceptor configuration.
/// Create Rustls v0.21 based service with custom TLS acceptor configuration.
pub fn rustls_021_with_config(
self,
mut config: ServerConfig,
@ -544,6 +554,102 @@ mod rustls_021 {
}
}
#[cfg(feature = "rustls-0_22")]
mod rustls_0_22 {
use std::io;
use actix_service::ServiceFactoryExt as _;
use actix_tls::accept::{
rustls_0_22::{reexports::ServerConfig, Acceptor, TlsStream},
TlsError,
};
use super::*;
impl<S, B, X, U> HttpService<TlsStream<TcpStream>, S, B, X, U>
where
S: ServiceFactory<Request, Config = ()>,
S::Future: 'static,
S::Error: Into<Response<BoxBody>> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
X: ServiceFactory<Request, Config = (), Response = Request>,
X::Future: 'static,
X::Error: Into<Response<BoxBody>>,
X::InitError: fmt::Debug,
U: ServiceFactory<
(Request, Framed<TlsStream<TcpStream>, h1::Codec>),
Config = (),
Response = (),
>,
U::Future: 'static,
U::Error: fmt::Display + Into<Response<BoxBody>>,
U::InitError: fmt::Debug,
{
/// Create Rustls v0.22 based service.
pub fn rustls_0_22(
self,
config: ServerConfig,
) -> impl ServiceFactory<
TcpStream,
Config = (),
Response = (),
Error = TlsError<io::Error, DispatchError>,
InitError = (),
> {
self.rustls_0_22_with_config(config, TlsAcceptorConfig::default())
}
/// Create Rustls v0.22 based service with custom TLS acceptor configuration.
pub fn rustls_0_22_with_config(
self,
mut config: ServerConfig,
tls_acceptor_config: TlsAcceptorConfig,
) -> impl ServiceFactory<
TcpStream,
Config = (),
Response = (),
Error = TlsError<io::Error, DispatchError>,
InitError = (),
> {
let mut protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
protos.extend_from_slice(&config.alpn_protocols);
config.alpn_protocols = protos;
let mut acceptor = Acceptor::new(config);
if let Some(handshake_timeout) = tls_acceptor_config.handshake_timeout {
acceptor.set_handshake_timeout(handshake_timeout);
}
acceptor
.map_init_err(|_| {
unreachable!("TLS acceptor service factory does not error on init")
})
.map_err(TlsError::into_service_error)
.and_then(|io: TlsStream<TcpStream>| async {
let proto = if let Some(protos) = io.get_ref().1.alpn_protocol() {
if protos.windows(2).any(|window| window == b"h2") {
Protocol::Http2
} else {
Protocol::Http1
}
} else {
Protocol::Http1
};
let peer_addr = io.get_ref().0.peer_addr().ok();
Ok((io, proto, peer_addr))
})
.and_then(self.map_err(TlsError::Service))
}
}
}
impl<T, S, B, X, U> ServiceFactory<(T, Protocol, Option<net::SocketAddr>)>
for HttpService<T, S, B, X, U>
where

View File

@ -296,7 +296,7 @@ impl Decoder for Codec {
}
}
Ok(None) => Ok(None),
Err(e) => Err(e),
Err(err) => Err(err),
}
}
}

View File

@ -1,5 +1,4 @@
#![cfg(feature = "openssl")]
#![allow(clippy::uninlined_format_args)]
extern crate tls_openssl as openssl;

View File

@ -1,6 +1,6 @@
#![cfg(feature = "rustls-0_21")]
#![cfg(feature = "rustls-0_22")]
extern crate tls_rustls_021 as rustls;
extern crate tls_rustls_022 as rustls;
use std::{
convert::Infallible,
@ -20,13 +20,13 @@ use actix_http::{
use actix_http_test::test_server;
use actix_rt::pin;
use actix_service::{fn_factory_with_config, fn_service};
use actix_tls::connect::rustls_0_21::webpki_roots_cert_store;
use actix_tls::connect::rustls_0_22::webpki_roots_cert_store;
use actix_utils::future::{err, ok, poll_fn};
use bytes::{Bytes, BytesMut};
use derive_more::{Display, Error};
use futures_core::{ready, Stream};
use futures_util::stream::once;
use rustls::{Certificate, PrivateKey, ServerConfig as RustlsServerConfig, ServerName};
use rustls::{pki_types::ServerName, ServerConfig as RustlsServerConfig};
use rustls_pemfile::{certs, pkcs8_private_keys};
async fn load_body<S>(stream: S) -> Result<BytesMut, PayloadError>
@ -59,17 +59,17 @@ fn tls_config() -> RustlsServerConfig {
let cert_file = &mut BufReader::new(cert_file.as_bytes());
let key_file = &mut BufReader::new(key_file.as_bytes());
let cert_chain = certs(cert_file)
.unwrap()
.into_iter()
.map(Certificate)
.collect();
let mut keys = pkcs8_private_keys(key_file).unwrap();
let cert_chain = certs(cert_file).collect::<Result<Vec<_>, _>>().unwrap();
let mut keys = pkcs8_private_keys(key_file)
.collect::<Result<Vec<_>, _>>()
.unwrap();
let mut config = RustlsServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth()
.with_single_cert(cert_chain, PrivateKey(keys.remove(0)))
.with_single_cert(
cert_chain,
rustls::pki_types::PrivateKeyDer::Pkcs8(keys.remove(0)),
)
.unwrap();
config.alpn_protocols.push(HTTP1_1_ALPN_PROTOCOL.to_vec());
@ -83,7 +83,6 @@ pub fn get_negotiated_alpn_protocol(
client_alpn_protocol: &[u8],
) -> Option<Vec<u8>> {
let mut config = rustls::ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(webpki_roots_cert_store())
.with_no_client_auth();
@ -109,7 +108,7 @@ async fn h1() -> io::Result<()> {
let srv = test_server(move || {
HttpService::build()
.h1(|_| ok::<_, Error>(Response::ok()))
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -123,7 +122,7 @@ async fn h2() -> io::Result<()> {
let srv = test_server(move || {
HttpService::build()
.h2(|_| ok::<_, Error>(Response::ok()))
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -141,7 +140,7 @@ async fn h1_1() -> io::Result<()> {
assert_eq!(req.version(), Version::HTTP_11);
ok::<_, Error>(Response::ok())
})
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -159,7 +158,7 @@ async fn h2_1() -> io::Result<()> {
assert_eq!(req.version(), Version::HTTP_2);
ok::<_, Error>(Response::ok())
})
.rustls_021_with_config(
.rustls_0_22_with_config(
tls_config(),
TlsAcceptorConfig::default().handshake_timeout(Duration::from_secs(5)),
)
@ -180,7 +179,7 @@ async fn h2_body1() -> io::Result<()> {
let body = load_body(req.take_payload()).await?;
Ok::<_, Error>(Response::ok().set_body(body))
})
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -206,7 +205,7 @@ async fn h2_content_length() {
];
ok::<_, Infallible>(Response::new(statuses[indx]))
})
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -278,7 +277,7 @@ async fn h2_headers() {
}
ok::<_, Infallible>(config.body(data.clone()))
})
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -317,7 +316,7 @@ async fn h2_body2() {
let mut srv = test_server(move || {
HttpService::build()
.h2(|_| ok::<_, Infallible>(Response::ok().set_body(STR)))
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -334,7 +333,7 @@ async fn h2_head_empty() {
let mut srv = test_server(move || {
HttpService::build()
.finish(|_| ok::<_, Infallible>(Response::ok().set_body(STR)))
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -360,7 +359,7 @@ async fn h2_head_binary() {
let mut srv = test_server(move || {
HttpService::build()
.h2(|_| ok::<_, Infallible>(Response::ok().set_body(STR)))
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -385,7 +384,7 @@ async fn h2_head_binary2() {
let srv = test_server(move || {
HttpService::build()
.h2(|_| ok::<_, Infallible>(Response::ok().set_body(STR)))
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -411,7 +410,7 @@ async fn h2_body_length() {
Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
)
})
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -435,7 +434,7 @@ async fn h2_body_chunked_explicit() {
.body(BodyStream::new(body)),
)
})
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -464,7 +463,7 @@ async fn h2_response_http_error_handling() {
)
}))
}))
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -494,7 +493,7 @@ async fn h2_service_error() {
let mut srv = test_server(move || {
HttpService::build()
.h2(|_| err::<Response<BoxBody>, _>(BadRequest))
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -511,7 +510,7 @@ async fn h1_service_error() {
let mut srv = test_server(move || {
HttpService::build()
.h1(|_| err::<Response<BoxBody>, _>(BadRequest))
.rustls_021(tls_config())
.rustls_0_22(tls_config())
})
.await;
@ -534,7 +533,7 @@ async fn alpn_h1() -> io::Result<()> {
config.alpn_protocols.push(CUSTOM_ALPN_PROTOCOL.to_vec());
HttpService::build()
.h1(|_| ok::<_, Error>(Response::ok()))
.rustls_021(config)
.rustls_0_22(config)
})
.await;
@ -556,7 +555,7 @@ async fn alpn_h2() -> io::Result<()> {
config.alpn_protocols.push(CUSTOM_ALPN_PROTOCOL.to_vec());
HttpService::build()
.h2(|_| ok::<_, Error>(Response::ok()))
.rustls_021(config)
.rustls_0_22(config)
})
.await;
@ -582,7 +581,7 @@ async fn alpn_h2_1() -> io::Result<()> {
config.alpn_protocols.push(CUSTOM_ALPN_PROTOCOL.to_vec());
HttpService::build()
.finish(|_| ok::<_, Error>(Response::ok()))
.rustls_021(config)
.rustls_0_22(config)
})
.await;

View File

@ -147,7 +147,7 @@ async fn chunked_payload() {
.take_payload()
.map(|res| match res {
Ok(pl) => pl,
Err(e) => panic!("Error reading payload: {}", e),
Err(err) => panic!("Error reading payload: {err}"),
})
.fold(0usize, |acc, chunk| ready(acc + chunk.len()))
.map(|req_size| {

View File

@ -1,5 +1,3 @@
#![allow(clippy::uninlined_format_args)]
use std::{
cell::Cell,
convert::Infallible,

View File

@ -5,7 +5,7 @@ authors = ["Jacob Halsey <jacob@jhalsey.com>"]
description = "Multipart form derive macro for Actix Web"
keywords = ["http", "web", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
repository = "https://github.com/actix/actix-web"
license = "MIT OR Apache-2.0"
edition = "2021"

View File

@ -1,16 +1,20 @@
# actix-multipart-derive
# `actix-multipart-derive`
> The derive macro implementation for actix-multipart-derive.
<!-- prettier-ignore-start -->
[![crates.io](https://img.shields.io/crates/v/actix-multipart-derive?label=latest)](https://crates.io/crates/actix-multipart-derive)
[![Documentation](https://docs.rs/actix-multipart-derive/badge.svg?version=0.5.0)](https://docs.rs/actix-multipart-derive/0.5.0)
[![Documentation](https://docs.rs/actix-multipart-derive/badge.svg?version=0.6.1)](https://docs.rs/actix-multipart-derive/0.6.1)
![Version](https://img.shields.io/badge/rustc-1.68+-ab6000.svg)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-multipart-derive.svg)
<br />
[![dependency status](https://deps.rs/crate/actix-multipart-derive/0.5.0/status.svg)](https://deps.rs/crate/actix-multipart-derive/0.5.0)
[![dependency status](https://deps.rs/crate/actix-multipart-derive/0.6.1/status.svg)](https://deps.rs/crate/actix-multipart-derive/0.6.1)
[![Download](https://img.shields.io/crates/d/actix-multipart-derive.svg)](https://crates.io/crates/actix-multipart-derive)
[![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x)
<!-- prettier-ignore-end -->
## Documentation & Resources
- [API Documentation](https://docs.rs/actix-multipart-derive)

View File

@ -8,7 +8,7 @@ authors = [
description = "Multipart form support for Actix Web"
keywords = ["http", "web", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
repository = "https://github.com/actix/actix-web"
license = "MIT OR Apache-2.0"
edition = "2021"

View File

@ -1,7 +1,9 @@
# actix-multipart
# `actix-multipart`
> Multipart form support for Actix Web.
<!-- prettier-ignore-start -->
[![crates.io](https://img.shields.io/crates/v/actix-multipart?label=latest)](https://crates.io/crates/actix-multipart)
[![Documentation](https://docs.rs/actix-multipart/badge.svg?version=0.6.1)](https://docs.rs/actix-multipart/0.6.1)
![Version](https://img.shields.io/badge/rustc-1.68+-ab6000.svg)
@ -11,6 +13,8 @@
[![Download](https://img.shields.io/crates/d/actix-multipart.svg)](https://crates.io/crates/actix-multipart)
[![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x)
<!-- prettier-ignore-end -->
## Documentation & Resources
- [API Documentation](https://docs.rs/actix-multipart)

View File

@ -2,7 +2,7 @@
#![deny(rust_2018_idioms, nonstandard_style)]
#![warn(future_incompatible)]
#![allow(clippy::borrow_interior_mutable_const, clippy::uninlined_format_args)]
#![allow(clippy::borrow_interior_mutable_const)]
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

View File

@ -2,6 +2,8 @@
## Unreleased
## 0.5.2
- Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency.
## 0.5.1

View File

@ -1,6 +1,6 @@
[package]
name = "actix-router"
version = "0.5.1"
version = "0.5.2"
authors = [
"Nikolay Kim <fafhrd91@gmail.com>",
"Ali MJ Al-Nasrawy <alimjalnasrawy@gmail.com>",
@ -8,7 +8,7 @@ authors = [
]
description = "Resource path matching and router"
keywords = ["actix", "router", "routing"]
repository = "https://github.com/actix/actix-web.git"
repository = "https://github.com/actix/actix-web"
license = "MIT OR Apache-2.0"
edition = "2021"

20
actix-router/README.md Normal file
View File

@ -0,0 +1,20 @@
# `actix-router`
<!-- prettier-ignore-start -->
[![crates.io](https://img.shields.io/crates/v/actix-router?label=latest)](https://crates.io/crates/actix-router)
[![Documentation](https://docs.rs/actix-router/badge.svg?version=0.5.2)](https://docs.rs/actix-router/0.5.2)
![Version](https://img.shields.io/badge/rustc-1.68+-ab6000.svg)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-router.svg)
<br />
[![dependency status](https://deps.rs/crate/actix-router/0.5.2/status.svg)](https://deps.rs/crate/actix-router/0.5.2)
[![Download](https://img.shields.io/crates/d/actix-router.svg)](https://crates.io/crates/actix-router)
[![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x)
<!-- prettier-ignore-end -->
<!-- cargo-rdme start -->
Resource path matching and router.
<!-- cargo-rdme end -->

View File

@ -1,5 +1,3 @@
#![allow(clippy::uninlined_format_args)]
use std::{borrow::Cow, fmt::Write as _};
use criterion::{black_box, criterion_group, criterion_main, Criterion};

View File

@ -2,7 +2,6 @@
#![deny(rust_2018_idioms, nonstandard_style)]
#![warn(future_incompatible)]
#![allow(clippy::uninlined_format_args)]
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

View File

@ -3,7 +3,7 @@ use std::{
ops::{DerefMut, Index},
};
use serde::de;
use serde::{de, Deserialize};
use crate::{de::PathDeserializer, Resource, ResourcePath};
@ -24,8 +24,13 @@ impl Default for PathItem {
/// If resource path contains variable patterns, `Path` stores them.
#[derive(Debug, Clone, Default)]
pub struct Path<T> {
/// Full path representation.
path: T,
/// Number of characters in `path` that have been processed into `segments`.
pub(crate) skip: u16,
/// List of processed dynamic segments; name->value pairs.
pub(crate) segments: Vec<(Cow<'static, str>, PathItem)>,
}
@ -83,8 +88,8 @@ impl<T: ResourcePath> Path<T> {
/// Set new path.
#[inline]
pub fn set(&mut self, path: T) {
self.skip = 0;
self.path = path;
self.skip = 0;
self.segments.clear();
}
@ -103,7 +108,7 @@ impl<T: ResourcePath> Path<T> {
pub(crate) fn add(&mut self, name: impl Into<Cow<'static, str>>, value: PathItem) {
match value {
PathItem::Static(s) => self.segments.push((name.into(), PathItem::Static(s))),
PathItem::Static(seg) => self.segments.push((name.into(), PathItem::Static(seg))),
PathItem::Segment(begin, end) => self.segments.push((
name.into(),
PathItem::Segment(self.skip + begin, self.skip + end),
@ -168,9 +173,13 @@ impl<T: ResourcePath> Path<T> {
}
}
/// Try to deserialize matching parameters to a specified type `U`
pub fn load<'de, U: serde::Deserialize<'de>>(&'de self) -> Result<U, de::value::Error> {
de::Deserialize::deserialize(PathDeserializer::new(self))
/// Deserializes matching parameters to a specified type `U`.
///
/// # Errors
///
/// Returns error when dynamic path segments cannot be deserialized into a `U` type.
pub fn load<'de, U: Deserialize<'de>>(&'de self) -> Result<U, de::value::Error> {
Deserialize::deserialize(PathDeserializer::new(self))
}
}

View File

@ -193,8 +193,8 @@ const REGEX_FLAGS: &str = "(?s-m)";
/// # Trailing Slashes
/// It should be noted that this library takes no steps to normalize intra-path or trailing slashes.
/// As such, all resource definitions implicitly expect a pre-processing step to normalize paths if
/// they you wish to accommodate "recoverable" path errors. Below are several examples of
/// resource-path pairs that would not be compatible.
/// you wish to accommodate "recoverable" path errors. Below are several examples of resource-path
/// pairs that would not be compatible.
///
/// ## Examples
/// ```

View File

@ -97,6 +97,7 @@ impl<T, U> RouterBuilder<T, U> {
ctx: U,
) -> (&mut ResourceDef, &mut T, &mut U) {
self.routes.push((rdef, val, ctx));
#[allow(clippy::map_identity)] // map is used to distribute &mut-ness to tuple elements
self.routes
.last_mut()
.map(|(rdef, val, ctx)| (rdef, val, ctx))
@ -186,11 +187,11 @@ mod tests {
assert_eq!(path.get("file").unwrap(), "file");
assert_eq!(path.get("ext").unwrap(), "gz");
let mut path = Path::new("/vtest/ttt/index.html");
let mut path = Path::new("/v2/ttt/index.html");
let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 14);
assert_eq!(info, ResourceId(4));
assert_eq!(path.get("val").unwrap(), "test");
assert_eq!(path.get("val").unwrap(), "2");
assert_eq!(path.get("val2").unwrap(), "ttt");
let mut path = Path::new("/v/blah-blah/index.html");

View File

@ -2,6 +2,10 @@
## Unreleased
## 0.1.3
- Add `TestServerConfig::rustls_0_22()` method for Rustls v0.22 support behind new `rustls-0_22` crate feature.
## 0.1.2
- Add `TestServerConfig::rustls_021()` method for Rustls v0.21 support behind new `rustls-0_21` crate feature.

View File

@ -1,6 +1,6 @@
[package]
name = "actix-test"
version = "0.1.2"
version = "0.1.3"
authors = [
"Nikolay Kim <fafhrd91@gmail.com>",
"Rob Ede <robjtede@icloud.com>",
@ -8,7 +8,7 @@ authors = [
description = "Integration testing tools for Actix Web applications"
keywords = ["http", "web", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
repository = "https://github.com/actix/actix-web"
categories = [
"network-programming",
"asynchronous",
@ -27,19 +27,21 @@ rustls = ["rustls-0_20"]
rustls-0_20 = ["tls-rustls-0_20", "actix-http/rustls-0_20", "awc/rustls-0_20"]
# TLS via Rustls v0.21
rustls-0_21 = ["tls-rustls-0_21", "actix-http/rustls-0_21", "awc/rustls-0_21"]
# TLS via Rustls v0.22
rustls-0_22 = ["tls-rustls-0_22", "actix-http/rustls-0_22", "awc/rustls-0_22-webpki-roots"]
# TLS via OpenSSL
openssl = ["tls-openssl", "actix-http/openssl", "awc/openssl"]
[dependencies]
actix-codec = "0.5"
actix-http = "3"
actix-http = "3.6"
actix-http-test = "3"
actix-rt = "2.1"
actix-service = "2"
actix-utils = "3"
actix-web = { version = "4", default-features = false, features = ["cookies"] }
awc = { version = "3", default-features = false, features = ["cookies"] }
actix-web = { version = "4.5", default-features = false, features = ["cookies"] }
awc = { version = "3.4", default-features = false, features = ["cookies"] }
futures-core = { version = "0.3.17", default-features = false, features = ["std"] }
futures-util = { version = "0.3.17", default-features = false, features = [] }
@ -50,4 +52,5 @@ serde_urlencoded = "0.7"
tls-openssl = { package = "openssl", version = "0.10.55", optional = true }
tls-rustls-0_20 = { package = "rustls", version = "0.20", optional = true }
tls-rustls-0_21 = { package = "rustls", version = "0.21", optional = true }
tls-rustls-0_22 = { package = "rustls", version = "0.22", optional = true }
tokio = { version = "1.24.2", features = ["sync"] }

View File

@ -143,6 +143,8 @@ where
StreamType::Rustls020(_) => true,
#[cfg(feature = "rustls-0_21")]
StreamType::Rustls021(_) => true,
#[cfg(feature = "rustls-0_22")]
StreamType::Rustls022(_) => true,
};
// run server in separate orphaned thread
@ -327,6 +329,48 @@ where
.rustls_021(config.clone())
}),
},
#[cfg(feature = "rustls-0_22")]
StreamType::Rustls022(config) => match cfg.tp {
HttpVer::Http1 => builder.listen("test", tcp, move || {
let app_cfg =
AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);
let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());
HttpService::build()
.client_request_timeout(timeout)
.h1(map_config(fac, move |_| app_cfg.clone()))
.rustls_0_22(config.clone())
}),
HttpVer::Http2 => builder.listen("test", tcp, move || {
let app_cfg =
AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);
let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());
HttpService::build()
.client_request_timeout(timeout)
.h2(map_config(fac, move |_| app_cfg.clone()))
.rustls_0_22(config.clone())
}),
HttpVer::Both => builder.listen("test", tcp, move || {
let app_cfg =
AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);
let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());
HttpService::build()
.client_request_timeout(timeout)
.finish(map_config(fac, move |_| app_cfg.clone()))
.rustls_0_22(config.clone())
}),
},
}
.expect("test server could not be created");
@ -401,6 +445,8 @@ enum StreamType {
Rustls020(tls_rustls_0_20::ServerConfig),
#[cfg(feature = "rustls-0_21")]
Rustls021(tls_rustls_0_21::ServerConfig),
#[cfg(feature = "rustls-0_22")]
Rustls022(tls_rustls_0_22::ServerConfig),
}
/// Create default test server config.
@ -424,7 +470,7 @@ impl Default for TestServerConfig {
}
impl TestServerConfig {
/// Create default server configuration
/// Constructs default server configuration.
pub(crate) fn new() -> TestServerConfig {
TestServerConfig {
tp: HttpVer::Both,
@ -435,40 +481,63 @@ impl TestServerConfig {
}
}
/// Accept HTTP/1.1 only.
/// Accepts HTTP/1.1 only.
pub fn h1(mut self) -> Self {
self.tp = HttpVer::Http1;
self
}
/// Accept HTTP/2 only.
/// Accepts HTTP/2 only.
pub fn h2(mut self) -> Self {
self.tp = HttpVer::Http2;
self
}
/// Accept secure connections via OpenSSL.
/// Accepts secure connections via OpenSSL.
#[cfg(feature = "openssl")]
pub fn openssl(mut self, acceptor: openssl::ssl::SslAcceptor) -> Self {
self.stream = StreamType::Openssl(acceptor);
self
}
/// Accept secure connections via Rustls.
#[doc(hidden)]
#[deprecated(note = "Renamed to `rustls_0_20()`.")]
#[cfg(feature = "rustls-0_20")]
pub fn rustls(mut self, config: tls_rustls_0_20::ServerConfig) -> Self {
self.stream = StreamType::Rustls020(config);
self
}
/// Accept secure connections via Rustls.
/// Accepts secure connections via Rustls v0.20.
#[cfg(feature = "rustls-0_20")]
pub fn rustls_0_20(mut self, config: tls_rustls_0_20::ServerConfig) -> Self {
self.stream = StreamType::Rustls020(config);
self
}
#[doc(hidden)]
#[deprecated(note = "Renamed to `rustls_0_21()`.")]
#[cfg(feature = "rustls-0_21")]
pub fn rustls_021(mut self, config: tls_rustls_0_21::ServerConfig) -> Self {
self.stream = StreamType::Rustls021(config);
self
}
/// Set client timeout for first request.
/// Accepts secure connections via Rustls v0.21.
#[cfg(feature = "rustls-0_21")]
pub fn rustls_0_21(mut self, config: tls_rustls_0_21::ServerConfig) -> Self {
self.stream = StreamType::Rustls021(config);
self
}
/// Accepts secure connections via Rustls v0.22.
#[cfg(feature = "rustls-0_22")]
pub fn rustls_0_22(mut self, config: tls_rustls_0_22::ServerConfig) -> Self {
self.stream = StreamType::Rustls022(config);
self
}
/// Sets client timeout for first request.
pub fn client_request_timeout(mut self, dur: Duration) -> Self {
self.client_request_timeout = dur;
self

View File

@ -2,6 +2,8 @@
## Unreleased
## 4.3.0
- Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency.
## 4.2.0

View File

@ -1,6 +1,6 @@
[package]
name = "actix-web-actors"
version = "4.2.0"
version = "4.3.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix actors support for Actix Web"
keywords = ["actix", "http", "web", "framework", "async"]

View File

@ -1,16 +1,20 @@
# actix-web-actors
# `actix-web-actors`
> Actix actors support for Actix Web.
<!-- prettier-ignore-start -->
[![crates.io](https://img.shields.io/crates/v/actix-web-actors?label=latest)](https://crates.io/crates/actix-web-actors)
[![Documentation](https://docs.rs/actix-web-actors/badge.svg?version=4.2.0)](https://docs.rs/actix-web-actors/4.2.0)
[![Documentation](https://docs.rs/actix-web-actors/badge.svg?version=4.3.0)](https://docs.rs/actix-web-actors/4.3.0)
![Version](https://img.shields.io/badge/rustc-1.68+-ab6000.svg)
![License](https://img.shields.io/crates/l/actix-web-actors.svg)
<br />
[![dependency status](https://deps.rs/crate/actix-web-actors/4.2.0/status.svg)](https://deps.rs/crate/actix-web-actors/4.2.0)
[![dependency status](https://deps.rs/crate/actix-web-actors/4.3.0/status.svg)](https://deps.rs/crate/actix-web-actors/4.3.0)
[![Download](https://img.shields.io/crates/d/actix-web-actors.svg)](https://crates.io/crates/actix-web-actors)
[![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x)
<!-- prettier-ignore-end -->
## Documentation & Resources
- [API Documentation](https://docs.rs/actix-web-actors)

View File

@ -57,7 +57,6 @@
#![deny(rust_2018_idioms, nonstandard_style)]
#![warn(future_incompatible)]
#![allow(clippy::uninlined_format_args)]
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

View File

@ -775,10 +775,10 @@ where
break;
}
Poll::Pending => break,
Poll::Ready(Some(Err(e))) => {
Poll::Ready(Some(Err(err))) => {
return Poll::Ready(Some(Err(ProtocolError::Io(io::Error::new(
io::ErrorKind::Other,
format!("{}", e),
format!("{err}"),
)))));
}
}

View File

@ -3,7 +3,7 @@ name = "actix-web-codegen"
version = "4.2.2"
description = "Routing and runtime macros for Actix Web"
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
repository = "https://github.com/actix/actix-web"
authors = [
"Nikolay Kim <fafhrd91@gmail.com>",
"Rob Ede <robjtede@icloud.com>",

View File

@ -1,7 +1,9 @@
# actix-web-codegen
# `actix-web-codegen`
> Routing and runtime macros for Actix Web.
<!-- prettier-ignore-start -->
[![crates.io](https://img.shields.io/crates/v/actix-web-codegen?label=latest)](https://crates.io/crates/actix-web-codegen)
[![Documentation](https://docs.rs/actix-web-codegen/badge.svg?version=4.2.2)](https://docs.rs/actix-web-codegen/4.2.2)
![Version](https://img.shields.io/badge/rustc-1.68+-ab6000.svg)
@ -11,6 +13,8 @@
[![Download](https://img.shields.io/crates/d/actix-web-codegen.svg)](https://crates.io/crates/actix-web-codegen)
[![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x)
<!-- prettier-ignore-end -->
## Documentation & Resources
- [API Documentation](https://docs.rs/actix-web-codegen)

View File

@ -2,6 +2,30 @@
## Unreleased
## 4.5.1
### Fixed
- Fix missing import when using enabling Rustls v0.22 support.
## 4.5.0
### Added
- Add `rustls-0_22` crate feature.
- Add `HttpServer::{bind_rustls_0_22, listen_rustls_0_22}()` builder methods.
## 4.4.1
### Changed
- Updated `zstd` dependency to `0.13`.
- Compression middleware now prefers brotli over zstd over gzip.
### Fixed
- Fix validation of `Json` extractor when `JsonConfig::validate_content_type()` is set to false.
## 4.4.0
### Added

View File

@ -1,11 +1,11 @@
[package]
name = "actix-web"
version = "4.4.0"
version = "4.5.1"
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>",
]
description = "Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust"
keywords = ["actix", "http", "web", "framework", "async"]
categories = [
"network-programming",
@ -14,15 +14,26 @@ categories = [
"web-programming::websocket"
]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
license = "MIT OR Apache-2.0"
repository = "https://github.com/actix/actix-web"
license.workspace = true
edition.workspace = true
rust-version.workspace = true
[package.metadata.docs.rs]
# features that docs.rs will build with
features = ["macros", "openssl", "rustls-0_20", "rustls-0_21", "compress-brotli", "compress-gzip", "compress-zstd", "cookies", "secure-cookies"]
rustdoc-args = ["--cfg", "docsrs"]
features = [
"macros",
"openssl",
"rustls-0_20",
"rustls-0_21",
"rustls-0_22",
"compress-brotli",
"compress-gzip",
"compress-zstd",
"cookies",
"secure-cookies",
]
[lib]
name = "actix_web"
@ -58,6 +69,8 @@ rustls = ["rustls-0_20"]
rustls-0_20 = ["http2", "actix-http/rustls-0_20", "actix-tls/accept", "actix-tls/rustls-0_20"]
# TLS via Rustls v0.21
rustls-0_21 = ["http2", "actix-http/rustls-0_21", "actix-tls/accept", "actix-tls/rustls-0_21"]
# TLS via Rustls v0.22
rustls-0_22 = ["http2", "actix-http/rustls-0_22", "actix-tls/accept", "actix-tls/rustls-0_22"]
# Internal (PRIVATE!) features used to aid testing and checking feature status.
# Don't rely on these whatsoever. They may disappear at anytime.
@ -73,9 +86,9 @@ actix-rt = { version = "2.6", default-features = false }
actix-server = "2"
actix-service = "2"
actix-utils = "3"
actix-tls = { version = "3.1", default-features = false, optional = true }
actix-tls = { version = "3.3", default-features = false, optional = true }
actix-http = { version = "3.4", features = ["ws"] }
actix-http = { version = "3.6", features = ["ws"] }
actix-router = "0.5"
actix-web-codegen = { version = "4.2", optional = true }
@ -122,7 +135,7 @@ static_assertions = "1"
tls-openssl = { package = "openssl", version = "0.10.55" }
tls-rustls = { package = "rustls", version = "0.21" }
tokio = { version = "1.24.2", features = ["rt-multi-thread", "macros"] }
zstd = "0.12"
zstd = "0.13"
[[test]]
name = "test_server"

View File

@ -372,13 +372,13 @@ You may need to review the [guidance on shared mutable state](https://docs.rs/ac
HttpServer::new(|| {
- App::new()
- .data(MyState::default())
- .service(hander)
- .service(handler)
+ let my_state: Data<MyState> = Data::new(MyState::default());
+
+ App::new()
+ .app_data(my_state)
+ .service(hander)
+ .service(handler)
})
```

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.4.0)](https://docs.rs/actix-web/4.4.0)
[![Documentation](https://docs.rs/actix-web/badge.svg?version=4.5.1)](https://docs.rs/actix-web/4.5.1)
![MSRV](https://img.shields.io/badge/rustc-1.68+-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.4.0/status.svg)](https://deps.rs/crate/actix-web/4.4.0)
[![Dependency Status](https://deps.rs/crate/actix-web/4.5.1/status.svg)](https://deps.rs/crate/actix-web/4.5.1)
<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/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web)

View File

@ -1,5 +1,3 @@
#![allow(clippy::uninlined_format_args)]
use actix_web::{web, App, HttpResponse};
use awc::Client;
use criterion::{criterion_group, criterion_main, Criterion};

View File

@ -1,5 +1,3 @@
#![allow(clippy::uninlined_format_args)]
use actix_web::{middleware, rt, web, App, HttpRequest, HttpServer};
async fn index(req: HttpRequest) -> &'static str {

View File

@ -1,5 +1,3 @@
#![allow(clippy::uninlined_format_args)]
use actix_web::{get, web, HttpRequest};
#[cfg(unix)]
use actix_web::{middleware, App, Error, HttpResponse, HttpServer};

View File

@ -129,6 +129,8 @@ where
///
/// Data items are constructed during application initialization, before the server starts
/// accepting requests.
///
/// The returned data value `D` is wrapped as [`Data<D>`].
pub fn data_factory<F, Out, D, E>(mut self, data: F) -> Self
where
F: Fn() -> Out + 'static,
@ -141,8 +143,8 @@ where
let fut = data();
async move {
match fut.await {
Err(e) => {
log::error!("Can not construct data instance: {:?}", e);
Err(err) => {
log::error!("Can not construct data instance: {err:?}");
Err(())
}
Ok(data) => {

View File

@ -32,8 +32,8 @@ pub(crate) type FnDataFactory =
/// Since the Actix Web router layers application data, the returned object will reference the
/// "closest" instance of the type. For example, if an `App` stores a `u32`, a nested `Scope`
/// also stores a `u32`, and the delegated request handler falls within that `Scope`, then
/// extracting a `web::<Data<u32>>` for that handler will return the `Scope`'s instance.
/// However, using the same router set up and a request that does not get captured by the `Scope`,
/// extracting a `web::Data<u32>` for that handler will return the `Scope`'s instance. However,
/// using the same router set up and a request that does not get captured by the `Scope`,
/// `web::<Data<u32>>` would return the `App`'s instance.
///
/// If route data is not set for a handler, using `Data<T>` extractor would cause a `500 Internal
@ -69,7 +69,7 @@ pub(crate) type FnDataFactory =
/// HttpResponse::Ok()
/// }
///
/// /// Alteratively, use the `HttpRequest::app_data` method to access data in a handler.
/// /// Alternatively, use the `HttpRequest::app_data` method to access data in a handler.
/// async fn index_alt(req: HttpRequest) -> impl Responder {
/// let data = req.app_data::<Data<Mutex<MyData>>>().unwrap();
/// let mut my_data = data.lock().unwrap();

View File

@ -175,8 +175,8 @@ where
let res = ready!(this.fut.poll(cx));
match res {
Ok(t) => Poll::Ready(Ok(Some(t))),
Err(e) => {
log::debug!("Error for Option<T> extractor: {}", e.into());
Err(err) => {
log::debug!("Error for Option<T> extractor: {}", err.into());
Poll::Ready(Ok(None))
}
}
@ -217,8 +217,8 @@ where
/// /// extract `Thing` from request
/// async fn index(supplied_thing: Result<Thing>) -> String {
/// match supplied_thing {
/// Ok(thing) => format!("Got thing: {:?}", thing),
/// Err(e) => format!("Error extracting thing: {}", e)
/// Ok(thing) => format!("Got thing: {thing:?}"),
/// Err(err) => format!("Error extracting thing: {err}"),
/// }
/// }
///
@ -355,7 +355,7 @@ mod tuple_from_req {
Poll::Ready(Ok(output)) => {
let _ = this.$T.as_mut().project_replace(ExtractFuture::Done { output });
},
Poll::Ready(Err(e)) => return Poll::Ready(Err(e.into())),
Poll::Ready(Err(err)) => return Poll::Ready(Err(err.into())),
Poll::Pending => ready = false,
},
ExtractProj::Done { .. } => {},

View File

@ -20,7 +20,7 @@ use crate::http::header::Accept;
pub struct Acceptable {
mime: mime::Mime,
/// Wether to match `*/*` mime type.
/// Whether to match `*/*` mime type.
///
/// Defaults to false because it's not very useful otherwise.
match_star_star: bool,

View File

@ -2,7 +2,7 @@ use actix_http::{header, uri::Uri, RequestHead};
use super::{Guard, GuardContext};
/// Creates a guard that matches requests targetting a specific host.
/// Creates a guard that matches requests targeting a specific host.
///
/// # Matching Host
/// This guard will:

View File

@ -10,10 +10,12 @@ use crate::{
/// The interface for request handlers.
///
/// # What Is A Request Handler
///
/// In short, a handler is just an async function that receives request-based arguments, in any
/// order, and returns something that can be converted to a response.
///
/// In particular, a request handler has three requirements:
///
/// 1. It is an async function (or a function/closure that returns an appropriate future);
/// 1. The function parameters (up to 12) implement [`FromRequest`];
/// 1. The async function (or future) resolves to a type that can be converted into an
@ -21,11 +23,15 @@ use crate::{
///
///
/// # Compiler Errors
///
/// If you get the error `the trait Handler<_> is not implemented`, then your handler does not
/// fulfill the _first_ of the above requirements. Missing other requirements manifest as errors on
/// implementing [`FromRequest`] and [`Responder`], respectively.
/// fulfill the _first_ of the above requirements. (It could also mean that you're attempting to use
/// a macro-routed handler in a manual routing context like `web::get().to(handler)`, which is not
/// supported). Breaking the other requirements manifests as errors on implementing [`FromRequest`]
/// and [`Responder`], respectively.
///
/// # How Do Handlers Receive Variable Numbers Of Arguments
///
/// Rest assured there is no macro magic here; it's just traits.
///
/// The first thing to note is that [`FromRequest`] is implemented for tuples (up to 12 in length).
@ -40,6 +46,7 @@ use crate::{
/// destructures the tuple into its component types and calls your handler function with them.
///
/// In pseudo-code the process looks something like this:
///
/// ```ignore
/// async fn my_handler(body: String, state: web::Data<MyState>) -> impl Responder {
/// ...

View File

@ -149,7 +149,7 @@ impl AcceptEncoding {
/// Extracts the most preferable encoding, accounting for [q-factor weighting].
///
/// If no q-factors are provided, the first encoding is chosen. Note that items without
/// If no q-factors are provided, we prefer brotli > zstd > gzip. Note that items without
/// q-factors are given the maximum preference value.
///
/// As per the spec, returns [`Preference::Any`] if acceptable list is empty. Though, if this is
@ -167,6 +167,7 @@ impl AcceptEncoding {
let mut max_item = None;
let mut max_pref = Quality::ZERO;
let mut max_rank = 0;
// uses manual max lookup loop since we want the first occurrence in the case of same
// preference but `Iterator::max_by_key` would give us the last occurrence
@ -174,9 +175,13 @@ impl AcceptEncoding {
for pref in &self.0 {
// only change if strictly greater
// equal items, even while unsorted, still have higher preference if they appear first
if pref.quality > max_pref {
let rank = encoding_rank(pref);
if (pref.quality, rank) > (max_pref, max_rank) {
max_pref = pref.quality;
max_item = Some(pref.item.clone());
max_rank = rank;
}
}
@ -203,6 +208,8 @@ impl AcceptEncoding {
/// Returns a sorted list of encodings from highest to lowest precedence, accounting
/// for [q-factor weighting].
///
/// If no q-factors are provided, we prefer brotli > zstd > gzip.
///
/// [q-factor weighting]: https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2
pub fn ranked(&self) -> Vec<Preference<Encoding>> {
self.ranked_items().map(|q| q.item).collect()
@ -210,21 +217,44 @@ impl AcceptEncoding {
fn ranked_items(&self) -> impl Iterator<Item = QualityItem<Preference<Encoding>>> {
if self.0.is_empty() {
return vec![].into_iter();
return Vec::new().into_iter();
}
let mut types = self.0.clone();
// use stable sort so items with equal q-factor retain listed order
types.sort_by(|a, b| {
// sort by q-factor descending
b.quality.cmp(&a.quality)
// sort by q-factor descending then server ranking descending
b.quality
.cmp(&a.quality)
.then(encoding_rank(b).cmp(&encoding_rank(a)))
});
types.into_iter()
}
}
/// Returns server-defined encoding ranking.
fn encoding_rank(qv: &QualityItem<Preference<Encoding>>) -> u8 {
// ensure that q=0 items are never sorted above identity encoding
// invariant: sorting methods calling this fn use first-on-equal approach
if qv.quality == Quality::ZERO {
return 0;
}
match qv.item {
Preference::Specific(Encoding::Known(ContentEncoding::Brotli)) => 5,
Preference::Specific(Encoding::Known(ContentEncoding::Zstd)) => 4,
Preference::Specific(Encoding::Known(ContentEncoding::Gzip)) => 3,
Preference::Specific(Encoding::Known(ContentEncoding::Deflate)) => 2,
Preference::Any => 0,
Preference::Specific(Encoding::Known(ContentEncoding::Identity)) => 0,
Preference::Specific(Encoding::Known(_)) => 1,
Preference::Specific(Encoding::Unknown(_)) => 1,
}
}
/// Returns true if "identity" is an acceptable encoding.
///
/// Internal algorithm relies on item list being in descending order of quality.
@ -377,11 +407,11 @@ mod tests {
);
assert_eq!(
test.negotiate([Encoding::gzip(), Encoding::brotli(), Encoding::identity()].iter()),
Some(Encoding::gzip())
Some(Encoding::brotli())
);
assert_eq!(
test.negotiate([Encoding::brotli(), Encoding::gzip(), Encoding::identity()].iter()),
Some(Encoding::gzip())
Some(Encoding::brotli())
);
}
@ -398,6 +428,9 @@ mod tests {
let test = accept_encoding!("br", "gzip", "*");
assert_eq!(test.ranked(), vec![enc("br"), enc("gzip"), enc("*")]);
let test = accept_encoding!("gzip", "br", "*");
assert_eq!(test.ranked(), vec![enc("br"), enc("gzip"), enc("*")]);
}
#[test]
@ -420,5 +453,8 @@ mod tests {
let test = accept_encoding!("br", "gzip", "*");
assert_eq!(test.preference().unwrap(), enc("br"));
let test = accept_encoding!("gzip", "br", "*");
assert_eq!(test.preference().unwrap(), enc("br"));
}
}

View File

@ -69,7 +69,6 @@
#![deny(rust_2018_idioms, nonstandard_style)]
#![warn(future_incompatible)]
#![allow(clippy::uninlined_format_args)]
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

View File

@ -373,7 +373,7 @@ mod tests {
.default_service(web::to(move || {
HttpResponse::Ok()
.insert_header((header::VARY, "x-test"))
.finish()
.body(TEXT_DATA)
}))
})
.await;
@ -429,4 +429,47 @@ mod tests {
assert_successful_identity_res_with_content_type(&res, "image/jpeg");
assert_eq!(test::read_body(res).await, TEXT_DATA.as_bytes());
}
#[actix_rt::test]
async fn prevents_compression_empty() {
let app = test::init_service({
App::new()
.wrap(Compress::default())
.default_service(web::to(move || HttpResponse::Ok().finish()))
})
.await;
let req = test::TestRequest::default()
.insert_header((header::ACCEPT_ENCODING, "gzip"))
.to_request();
let res = test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::OK);
assert!(!res.headers().contains_key(header::CONTENT_ENCODING));
assert!(test::read_body(res).await.is_empty());
}
}
#[cfg(feature = "compress-brotli")]
#[cfg(test)]
mod tests_brotli {
use super::*;
use crate::{test, web, App};
#[actix_rt::test]
async fn prevents_compression_empty() {
let app = test::init_service({
App::new()
.wrap(Compress::default())
.default_service(web::to(move || HttpResponse::Ok().finish()))
})
.await;
let req = test::TestRequest::default()
.insert_header((header::ACCEPT_ENCODING, "br"))
.to_request();
let res = test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::OK);
assert!(!res.headers().contains_key(header::CONTENT_ENCODING));
assert!(test::read_body(res).await.is_empty());
}
}

View File

@ -356,7 +356,7 @@ where
let res = match ready!(this.fut.poll(cx)) {
Ok(res) => res,
Err(e) => return Poll::Ready(Err(e)),
Err(err) => return Poll::Ready(Err(err)),
};
if let Some(error) = res.response().error() {

View File

@ -72,7 +72,7 @@
//! processes the request as well and passes it to `MiddlewareA`, which then passes it to the
//! [`Service`]. In the [`Service`], the extractors will run first. They don't pass the request on,
//! but only view it (see [`FromRequest`]). After the [`Service`] responds to the request, the
//! response it passed back through `MiddlewareA`, `MiddlewareB`, and `MiddlewareC`.
//! response is passed back through `MiddlewareA`, `MiddlewareB`, and `MiddlewareC`.
//!
//! As you register middleware using [`wrap`][crate::App::wrap] and [`wrap_fn`][crate::App::wrap_fn]
//! in the [`App`] builder, imagine wrapping layers around an inner [`App`]. The first middleware

View File

@ -171,7 +171,7 @@ impl Responder for Redirect {
} else {
log::error!(
"redirect target location can not be converted to header value: {:?}",
self.to
self.to,
);
}

View File

@ -64,7 +64,7 @@ impl HttpResponseBuilder {
Ok((key, value)) => {
parts.headers.insert(key, value);
}
Err(e) => self.error = Some(e.into()),
Err(err) => self.error = Some(err.into()),
};
}
@ -86,7 +86,7 @@ impl HttpResponseBuilder {
if let Some(parts) = self.inner() {
match header.try_into_pair() {
Ok((key, value)) => parts.headers.append(key, value),
Err(e) => self.error = Some(e.into()),
Err(err) => self.error = Some(err.into()),
};
}
@ -210,7 +210,7 @@ impl HttpResponseBuilder {
Ok(value) => {
parts.headers.insert(header::CONTENT_TYPE, value);
}
Err(e) => self.error = Some(e.into()),
Err(err) => self.error = Some(err.into()),
};
}
self

View File

@ -5,8 +5,6 @@ mod responder;
#[allow(clippy::module_inception)]
mod response;
#[cfg(feature = "cookies")]
pub use self::response::CookieIter;
pub use self::{
builder::HttpResponseBuilder, customize_responder::CustomizeResponder, responder::Responder,
response::HttpResponse,

View File

@ -5,6 +5,7 @@
//! architecture in [`actix-rt`]'s docs.
//!
//! # Running Actix Web Without Macros
//!
//! ```no_run
//! use actix_web::{middleware, rt, web, App, HttpRequest, HttpServer};
//!
@ -25,6 +26,7 @@
//! ```
//!
//! # Running Actix Web Using `#[tokio::main]`
//!
//! If you need to run something that uses Tokio's work stealing functionality alongside Actix Web,
//! you can run Actix Web under `#[tokio::main]`. The [`Server`](crate::dev::Server) object returned
//! from [`HttpServer::run`](crate::HttpServer::run) can also be [`spawn`]ed, if preferred.
@ -32,6 +34,10 @@
//! Note that `actix` actor support (and therefore WebSocket support through `actix-web-actors`)
//! still require `#[actix_web::main]` since they require a [`System`] to be set up.
//!
//! Also note that calls to this module's [`spawn()`] re-export require an `#[actix_web::main]`
//! runtime (or a manually configured `LocalSet`) since it makes calls into to the current thread's
//! `LocalSet`, which `#[tokio::main]` does not set up.
//!
//! ```no_run
//! use actix_web::{get, middleware, rt, web, App, HttpRequest, HttpServer};
//!

View File

@ -7,7 +7,12 @@ use std::{
time::Duration,
};
#[cfg(any(feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21"))]
#[cfg(any(
feature = "openssl",
feature = "rustls-0_20",
feature = "rustls-0_21",
feature = "rustls-0_22",
))]
use actix_http::TlsAcceptorConfig;
use actix_http::{body::MessageBody, Extensions, HttpService, KeepAlive, Request, Response};
use actix_server::{Server, ServerBuilder};
@ -99,6 +104,12 @@ where
B: MessageBody + 'static,
{
/// Create new HTTP server with application factory
///
/// # Worker Count
///
/// The `factory` will be instantiated multiple times in most configurations. See
/// [`bind()`](Self::bind()) docs for more on how worker count and bind address resolution
/// causes multiple server factory instantiations.
pub fn new(factory: F) -> Self {
HttpServer {
factory,
@ -119,7 +130,18 @@ where
/// Sets number of workers to start (per bind address).
///
/// By default, the number of available physical CPUs is used as the worker count.
/// The default worker count is the determined by [`std::thread::available_parallelism()`]. See
/// its documentation to determine what behavior you should expect when server is run.
///
/// Note that the server factory passed to [`new`](Self::new()) will be instantiated **at least
/// once per worker**. See [`bind()`](Self::bind()) docs for more on how worker count and bind
/// address resolution causes multiple server factory instantiations.
///
/// `num` must be greater than 0.
///
/// # Panics
///
/// Panics if `num` is 0.
pub fn workers(mut self, num: usize) -> Self {
self.builder = self.builder.workers(num);
self
@ -319,23 +341,41 @@ where
/// Resolves socket address(es) and binds server to created listener(s).
///
/// # Hostname Resolution
/// When `addr` includes a hostname, it is possible for this method to bind to both the IPv4 and
/// IPv6 addresses that result from a DNS lookup. You can test this by passing `localhost:8080`
/// and noting that the server binds to `127.0.0.1:8080` _and_ `[::1]:8080`. To bind additional
/// addresses, call this method multiple times.
///
/// When `addrs` includes a hostname, it is possible for this method to bind to both the IPv4
/// and IPv6 addresses that result from a DNS lookup. You can test this by passing
/// `localhost:8080` and noting that the server binds to `127.0.0.1:8080` _and_ `[::1]:8080`. To
/// bind additional addresses, call this method multiple times.
///
/// Note that, if a DNS lookup is required, resolving hostnames is a blocking operation.
///
/// # Worker Count
///
/// The `factory` will be instantiated multiple times in most scenarios. The number of
/// instantiations is number of [`workers`](Self::workers()) × number of sockets resolved by
/// `addrs`.
///
/// For example, if you've manually set [`workers`](Self::workers()) to 2, and use `127.0.0.1`
/// as the bind `addrs`, then `factory` will be instantiated twice. However, using `localhost`
/// as the bind `addrs` can often resolve to both `127.0.0.1` (IPv4) _and_ `::1` (IPv6), causing
/// the `factory` to be instantiated 4 times (2 workers × 2 bind addresses).
///
/// Using a bind address of `0.0.0.0`, which signals to use all interfaces, may also multiple
/// the number of instantiations in a similar way.
///
/// # Typical Usage
///
/// In general, use `127.0.0.1:<port>` when testing locally and `0.0.0.0:<port>` when deploying
/// (with or without a reverse proxy or load balancer) so that the server is accessible.
///
/// # Errors
///
/// Returns an `io::Error` if:
/// - `addrs` cannot be resolved into one or more socket addresses;
/// - all the resolved socket addresses are already bound.
///
/// # Example
///
/// ```
/// # use actix_web::{App, HttpServer};
/// # fn inner() -> std::io::Result<()> {
@ -356,6 +396,8 @@ where
/// Resolves socket address(es) and binds server to created listener(s) for plaintext HTTP/1.x
/// or HTTP/2 connections.
///
/// See [`bind()`](Self::bind()) for more details on `addrs` argument.
#[cfg(feature = "http2")]
pub fn bind_auto_h2c<A: net::ToSocketAddrs>(mut self, addrs: A) -> io::Result<Self> {
let sockets = bind_addrs(addrs, self.backlog)?;
@ -370,7 +412,7 @@ where
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
/// using Rustls v0.20.
///
/// See [`bind()`](Self::bind) for more details on `addrs` argument.
/// See [`bind()`](Self::bind()) for more details on `addrs` argument.
///
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
#[cfg(feature = "rustls-0_20")]
@ -389,7 +431,7 @@ where
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
/// using Rustls v0.21.
///
/// See [`bind()`](Self::bind) for more details on `addrs` argument.
/// See [`bind()`](Self::bind()) for more details on `addrs` argument.
///
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
#[cfg(feature = "rustls-0_21")]
@ -405,10 +447,29 @@ where
Ok(self)
}
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
/// using Rustls v0.22.
///
/// See [`bind()`](Self::bind()) for more details on `addrs` argument.
///
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
#[cfg(feature = "rustls-0_22")]
pub fn bind_rustls_0_22<A: net::ToSocketAddrs>(
mut self,
addrs: A,
config: actix_tls::accept::rustls_0_22::reexports::ServerConfig,
) -> io::Result<Self> {
let sockets = bind_addrs(addrs, self.backlog)?;
for lst in sockets {
self = self.listen_rustls_0_22_inner(lst, config.clone())?;
}
Ok(self)
}
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
/// using OpenSSL.
///
/// See [`bind()`](Self::bind) for more details on `addrs` argument.
/// See [`bind()`](Self::bind()) for more details on `addrs` argument.
///
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
#[cfg(feature = "openssl")]
@ -648,6 +709,72 @@ where
Ok(self)
}
/// Binds to existing listener for accepting incoming TLS connection requests using Rustls
/// v0.22.
///
/// See [`listen()`](Self::listen) for more details on the `lst` argument.
///
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
#[cfg(feature = "rustls-0_22")]
pub fn listen_rustls_0_22(
self,
lst: net::TcpListener,
config: actix_tls::accept::rustls_0_22::reexports::ServerConfig,
) -> io::Result<Self> {
self.listen_rustls_0_22_inner(lst, config)
}
#[cfg(feature = "rustls-0_22")]
fn listen_rustls_0_22_inner(
mut self,
lst: net::TcpListener,
config: actix_tls::accept::rustls_0_22::reexports::ServerConfig,
) -> io::Result<Self> {
let factory = self.factory.clone();
let cfg = self.config.clone();
let addr = lst.local_addr().unwrap();
self.sockets.push(Socket {
addr,
scheme: "https",
});
let on_connect_fn = self.on_connect_fn.clone();
self.builder =
self.builder
.listen(format!("actix-web-service-{}", addr), lst, move || {
let c = cfg.lock().unwrap();
let host = c.host.clone().unwrap_or_else(|| format!("{}", addr));
let svc = HttpService::build()
.keep_alive(c.keep_alive)
.client_request_timeout(c.client_request_timeout)
.client_disconnect_timeout(c.client_disconnect_timeout);
let svc = if let Some(handler) = on_connect_fn.clone() {
svc.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext))
} else {
svc
};
let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());
let acceptor_config = match c.tls_handshake_timeout {
Some(dur) => TlsAcceptorConfig::default().handshake_timeout(dur),
None => TlsAcceptorConfig::default(),
};
svc.finish(map_config(fac, move |_| {
AppConfig::new(true, host.clone(), addr)
}))
.rustls_0_22_with_config(config.clone(), acceptor_config)
})?;
Ok(self)
}
/// Binds to existing listener for accepting incoming TLS connection requests using OpenSSL.
///
/// See [`listen()`](Self::listen) for more details on the `lst` argument.
@ -853,7 +980,7 @@ fn bind_addrs(addrs: impl net::ToSocketAddrs, backlog: u32) -> io::Result<Vec<ne
success = true;
sockets.push(lst);
}
Err(e) => err = Some(e),
Err(error) => err = Some(error),
}
}

View File

@ -221,12 +221,9 @@ impl ServiceRequest {
/// Returns peer's socket address.
///
/// Peer address is the directly connected peer's socket address. If a proxy is used in front of
/// the Actix Web server, then it would be address of this proxy.
/// See [`HttpRequest::peer_addr`] for more details.
///
/// To get client connection information `ConnectionInfo` should be used.
///
/// Will only return None when called in unit tests.
/// [`HttpRequest::peer_addr`]: crate::HttpRequest::peer_addr
#[inline]
pub fn peer_addr(&self) -> Option<net::SocketAddr> {
self.head().peer_addr

View File

@ -86,76 +86,77 @@ impl Default for TestRequest {
#[allow(clippy::wrong_self_convention)]
impl TestRequest {
/// Create TestRequest and set request uri
pub fn with_uri(path: &str) -> TestRequest {
TestRequest::default().uri(path)
/// Constructs test request and sets request URI.
pub fn with_uri(uri: &str) -> TestRequest {
TestRequest::default().uri(uri)
}
/// Create TestRequest and set method to `Method::GET`
/// Constructs test request with GET method.
pub fn get() -> TestRequest {
TestRequest::default().method(Method::GET)
}
/// Create TestRequest and set method to `Method::POST`
/// Constructs test request with POST method.
pub fn post() -> TestRequest {
TestRequest::default().method(Method::POST)
}
/// Create TestRequest and set method to `Method::PUT`
/// Constructs test request with PUT method.
pub fn put() -> TestRequest {
TestRequest::default().method(Method::PUT)
}
/// Create TestRequest and set method to `Method::PATCH`
/// Constructs test request with PATCH method.
pub fn patch() -> TestRequest {
TestRequest::default().method(Method::PATCH)
}
/// Create TestRequest and set method to `Method::DELETE`
/// Constructs test request with DELETE method.
pub fn delete() -> TestRequest {
TestRequest::default().method(Method::DELETE)
}
/// Set HTTP version of this request
/// Sets HTTP version of this request.
pub fn version(mut self, ver: Version) -> Self {
self.req.version(ver);
self
}
/// Set HTTP method of this request
/// Sets method of this request.
pub fn method(mut self, meth: Method) -> Self {
self.req.method(meth);
self
}
/// Set HTTP URI of this request
/// Sets URI of this request.
pub fn uri(mut self, path: &str) -> Self {
self.req.uri(path);
self
}
/// Insert a header, replacing any that were set with an equivalent field name.
/// Inserts a header, replacing any that were set with an equivalent field name.
pub fn insert_header(mut self, header: impl TryIntoHeaderPair) -> Self {
self.req.insert_header(header);
self
}
/// Append a header, keeping any that were set with an equivalent field name.
/// Appends a header, keeping any that were set with an equivalent field name.
pub fn append_header(mut self, header: impl TryIntoHeaderPair) -> Self {
self.req.append_header(header);
self
}
/// Set cookie for this request.
/// Sets cookie for this request.
#[cfg(feature = "cookies")]
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
self.cookies.add(cookie.into_owned());
self
}
/// Set request path pattern parameter.
/// Sets request path pattern parameter.
///
/// # Examples
///
/// ```
/// use actix_web::test::TestRequest;
///
@ -171,19 +172,19 @@ impl TestRequest {
self
}
/// Set peer addr.
/// Sets peer address.
pub fn peer_addr(mut self, addr: SocketAddr) -> Self {
self.peer_addr = Some(addr);
self
}
/// Set request payload.
/// Sets request payload.
pub fn set_payload(mut self, data: impl Into<Bytes>) -> Self {
self.req.set_payload(data);
self
}
/// Serialize `data` to a URL encoded form and set it as the request payload.
/// Serializes `data` to a URL encoded form and set it as the request payload.
///
/// The `Content-Type` header is set to `application/x-www-form-urlencoded`.
pub fn set_form(mut self, data: impl Serialize) -> Self {
@ -194,7 +195,7 @@ impl TestRequest {
self
}
/// Serialize `data` to JSON and set it as the request payload.
/// Serializes `data` to JSON and set it as the request payload.
///
/// The `Content-Type` header is set to `application/json`.
pub fn set_json(mut self, data: impl Serialize) -> Self {
@ -204,27 +205,33 @@ impl TestRequest {
self
}
/// Set application data. This is equivalent of `App::data()` method
/// for testing purpose.
pub fn data<T: 'static>(mut self, data: T) -> Self {
self.app_data.insert(Data::new(data));
self
}
/// Set application data. This is equivalent of `App::app_data()` method
/// for testing purpose.
/// Inserts application data.
///
/// This is equivalent of `App::app_data()` method for testing purpose.
pub fn app_data<T: 'static>(mut self, data: T) -> Self {
self.app_data.insert(data);
self
}
/// Inserts application data.
///
/// This is equivalent of `App::data()` method for testing purpose.
#[doc(hidden)]
pub fn data<T: 'static>(mut self, data: T) -> Self {
self.app_data.insert(Data::new(data));
self
}
/// Sets resource map.
#[cfg(test)]
/// Set request config
pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
self.rmap = rmap;
self
}
/// Finalizes test request.
///
/// This request builder will be useless after calling `finish()`.
fn finish(&mut self) -> Request {
// mut used when cookie feature is enabled
#[allow(unused_mut)]
@ -251,14 +258,14 @@ impl TestRequest {
req
}
/// Complete request creation and generate `Request` instance
/// Finalizes request creation and returns `Request` instance.
pub fn to_request(mut self) -> Request {
let mut req = self.finish();
req.head_mut().peer_addr = self.peer_addr;
req
}
/// Complete request creation and generate `ServiceRequest` instance
/// Finalizes request creation and returns `ServiceRequest` instance.
pub fn to_srv_request(mut self) -> ServiceRequest {
let (mut head, payload) = self.finish().into_parts();
head.peer_addr = self.peer_addr;
@ -279,12 +286,12 @@ impl TestRequest {
)
}
/// Complete request creation and generate `ServiceResponse` instance
/// Finalizes request creation and returns `ServiceResponse` instance.
pub fn to_srv_response<B>(self, res: HttpResponse<B>) -> ServiceResponse<B> {
self.to_srv_request().into_response(res)
}
/// Complete request creation and generate `HttpRequest` instance
/// Finalizes request creation and returns `HttpRequest` instance.
pub fn to_http_request(mut self) -> HttpRequest {
let (mut head, _) = self.finish().into_parts();
head.peer_addr = self.peer_addr;
@ -302,7 +309,7 @@ impl TestRequest {
)
}
/// Complete request creation and generate `HttpRequest` and `Payload` instances
/// Finalizes request creation and returns `HttpRequest` and `Payload` pair.
pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
let (mut head, payload) = self.finish().into_parts();
head.peer_addr = self.peer_addr;
@ -322,7 +329,7 @@ impl TestRequest {
(req, payload)
}
/// Complete request creation, calls service and waits for response future completion.
/// Finalizes request creation, calls service, and waits for response future completion.
pub async fn send_request<S, B, E>(self, app: &S) -> S::Response
where
S: Service<Request, Response = ServiceResponse<B>, Error = E>,

View File

@ -2,7 +2,7 @@
use std::{fmt, ops};
use actix_utils::future::{err, ok, Ready};
use actix_utils::future::{ready, Ready};
use crate::{
dev::Payload, error::ParseError, extract::FromRequest, http::header::Header as ParseHeader,
@ -66,8 +66,8 @@ where
#[inline]
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
match ParseHeader::parse(req) {
Ok(header) => ok(Header(header)),
Err(e) => err(e),
Ok(header) => ready(Ok(Header(header))),
Err(err) => ready(Err(err)),
}
}
}

View File

@ -328,14 +328,19 @@ impl<T: DeserializeOwned> JsonBody<T> {
ctype_required: bool,
) -> Self {
// check content-type
let can_parse_json = if let Ok(Some(mime)) = req.mime_type() {
mime.subtype() == mime::JSON
|| mime.suffix() == Some(mime::JSON)
|| ctype_fn.map_or(false, |predicate| predicate(mime))
} else {
// if `ctype_required` is false, assume payload is
// json even when content-type header is missing
!ctype_required
let can_parse_json = match (ctype_required, req.mime_type()) {
(true, Ok(Some(mime))) => {
mime.subtype() == mime::JSON
|| mime.suffix() == Some(mime::JSON)
|| ctype_fn.map_or(false, |predicate| predicate(mime))
}
// if content-type is expected but not parsable as mime type, bail
(true, _) => false,
// if content-type validation is disabled, assume payload is JSON
// even when content-type header is missing or invalid mime type
(false, _) => true,
};
if !can_parse_json {
@ -725,6 +730,25 @@ mod tests {
assert!(s.is_ok())
}
#[actix_rt::test]
async fn test_json_ignoring_content_type() {
let (req, mut pl) = TestRequest::default()
.insert_header((
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
))
.insert_header((
header::CONTENT_TYPE,
header::HeaderValue::from_static("invalid/value"),
))
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.app_data(JsonConfig::default().content_type_required(false))
.to_http_parts();
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
assert!(s.is_ok());
}
#[actix_rt::test]
async fn test_with_config_in_data_wrapper() {
let (req, mut pl) = TestRequest::default()

View File

@ -96,7 +96,7 @@ async fn negotiate_encoding_gzip() {
let req = srv
.post("/static")
.insert_header((header::ACCEPT_ENCODING, "gzip,br,zstd"))
.insert_header((header::ACCEPT_ENCODING, "gzip, br;q=0.8, zstd;q=0.5"))
.send();
let mut res = req.await.unwrap();
@ -109,7 +109,7 @@ async fn negotiate_encoding_gzip() {
let mut res = srv
.post("/static")
.no_decompress()
.insert_header((header::ACCEPT_ENCODING, "gzip,br,zstd"))
.insert_header((header::ACCEPT_ENCODING, "gzip, br;q=0.8, zstd;q=0.5"))
.send()
.await
.unwrap();
@ -123,9 +123,11 @@ async fn negotiate_encoding_gzip() {
async fn negotiate_encoding_br() {
let srv = test_server!();
// check that brotli content-encoding header is returned
let req = srv
.post("/static")
.insert_header((header::ACCEPT_ENCODING, "br,zstd,gzip"))
.insert_header((header::ACCEPT_ENCODING, "br, zstd, gzip"))
.send();
let mut res = req.await.unwrap();
@ -135,10 +137,26 @@ async fn negotiate_encoding_br() {
let bytes = res.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(LOREM));
// check that brotli is preferred even when later in (q-less) list
let req = srv
.post("/static")
.insert_header((header::ACCEPT_ENCODING, "gzip, zstd, br"))
.send();
let mut res = req.await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.headers().get(header::CONTENT_ENCODING).unwrap(), "br");
let bytes = res.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(LOREM));
// check that returned content is actually brotli encoded
let mut res = srv
.post("/static")
.no_decompress()
.insert_header((header::ACCEPT_ENCODING, "br,zstd,gzip"))
.insert_header((header::ACCEPT_ENCODING, "br, zstd, gzip"))
.send()
.await
.unwrap();
@ -154,7 +172,7 @@ async fn negotiate_encoding_zstd() {
let req = srv
.post("/static")
.insert_header((header::ACCEPT_ENCODING, "zstd,gzip,br"))
.insert_header((header::ACCEPT_ENCODING, "zstd, gzip, br;q=0.8"))
.send();
let mut res = req.await.unwrap();
@ -167,7 +185,7 @@ async fn negotiate_encoding_zstd() {
let mut res = srv
.post("/static")
.no_decompress()
.insert_header((header::ACCEPT_ENCODING, "zstd,gzip,br"))
.insert_header((header::ACCEPT_ENCODING, "zstd, gzip, br;q=0.8"))
.send()
.await
.unwrap();
@ -207,7 +225,7 @@ async fn gzip_no_decompress() {
// don't decompress response body
.no_decompress()
// signal that we want a compressed body
.insert_header((header::ACCEPT_ENCODING, "gzip,br,zstd"))
.insert_header((header::ACCEPT_ENCODING, "gzip, br;q=0.8, zstd;q=0.5"))
.send();
let mut res = req.await.unwrap();

View File

@ -1,5 +1,3 @@
#![allow(clippy::uninlined_format_args)]
#[cfg(feature = "openssl")]
extern crate tls_openssl as openssl;

View File

@ -743,7 +743,7 @@ mod plus_rustls {
.map(char::from)
.collect::<String>();
let srv = actix_test::start_with(actix_test::config().rustls_021(tls_config()), || {
let srv = actix_test::start_with(actix_test::config().rustls_0_21(tls_config()), || {
App::new().service(web::resource("/").route(web::to(|bytes: Bytes| async {
// echo decompressed request body back in response
HttpResponse::Ok()

View File

@ -2,6 +2,16 @@
## Unreleased
## 3.4.0
- Add `rustls-0_22-webpki-roots` and `rustls-0_22-native-roots` crate feature.
- Add `awc::Connector::rustls_0_22()` method.
## 3.3.0
- Update `trust-dns-resolver` dependency to `0.23`.
- Updated `zstd` dependency to `0.13`.
## 3.2.0
- Add `awc::Connector::rustls_021()` method for Rustls v0.21 support behind new `rustls-0_21` crate feature.

View File

@ -1,6 +1,6 @@
[package]
name = "awc"
version = "3.2.0"
version = "3.4.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Async HTTP and WebSocket client library"
keywords = ["actix", "http", "framework", "async", "web"]
@ -11,7 +11,7 @@ categories = [
"web-programming::websocket",
]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
repository = "https://github.com/actix/actix-web"
license = "MIT OR Apache-2.0"
edition = "2021"
@ -20,8 +20,17 @@ name = "awc"
path = "src/lib.rs"
[package.metadata.docs.rs]
# features that docs.rs will build with
features = ["openssl", "rustls-0_20", "rustls-0_21", "compress-brotli", "compress-gzip", "compress-zstd", "cookies"]
rustdoc-args = ["--cfg", "docsrs"]
features = [
"cookies",
"openssl",
"rustls-0_20",
"rustls-0_21",
"rustls-0_22-webpki-roots",
"compress-brotli",
"compress-gzip",
"compress-zstd",
]
[features]
default = ["compress-brotli", "compress-gzip", "compress-zstd", "cookies"]
@ -35,6 +44,10 @@ rustls = ["rustls-0_20"]
rustls-0_20 = ["tls-rustls-0_20", "actix-tls/rustls-0_20"]
# TLS via Rustls v0.21
rustls-0_21 = ["tls-rustls-0_21", "actix-tls/rustls-0_21"]
# TLS via Rustls v0.22 (WebPKI roots)
rustls-0_22-webpki-roots = ["tls-rustls-0_22", "actix-tls/rustls-0_22-webpki-roots"]
# TLS via Rustls v0.22 (Native roots)
rustls-0_22-native-roots = ["tls-rustls-0_22", "actix-tls/rustls-0_22-native-roots"]
# Brotli algorithm content-encoding support
compress-brotli = ["actix-http/compress-brotli", "__compress"]
@ -61,9 +74,9 @@ dangerous-h2c = []
[dependencies]
actix-codec = "0.5"
actix-service = "2"
actix-http = { version = "3.4", features = ["http2", "ws"] }
actix-http = { version = "3.6", features = ["http2", "ws"] }
actix-rt = { version = "2.1", default-features = false }
actix-tls = { version = "3.1", features = ["connect", "uri"] }
actix-tls = { version = "3.3", features = ["connect", "uri"] }
actix-utils = "3"
base64 = "0.21"
@ -72,7 +85,7 @@ cfg-if = "1"
derive_more = "0.99.5"
futures-core = { version = "0.3.17", default-features = false, features = ["alloc"] }
futures-util = { version = "0.3.17", default-features = false, features = ["alloc", "sink"] }
h2 = "0.3.17"
h2 = "0.3.24"
http = "0.2.7"
itoa = "1"
log =" 0.4"
@ -90,15 +103,16 @@ cookie = { version = "0.16", features = ["percent-encode"], optional = true }
tls-openssl = { package = "openssl", version = "0.10.55", optional = true }
tls-rustls-0_20 = { package = "rustls", version = "0.20", optional = true, features = ["dangerous_configuration"] }
tls-rustls-0_21 = { package = "rustls", version = "0.21", optional = true, features = ["dangerous_configuration"] }
tls-rustls-0_22 = { package = "rustls", version = "0.22", optional = true }
trust-dns-resolver = { version = "0.22", optional = true }
trust-dns-resolver = { version = "0.23", optional = true }
[dev-dependencies]
actix-http = { version = "3.4", features = ["openssl"] }
actix-http = { version = "3.6", features = ["openssl"] }
actix-http-test = { version = "3", features = ["openssl"] }
actix-server = "2"
actix-test = { version = "0.1", features = ["openssl", "rustls-0_21"] }
actix-tls = { version = "3", features = ["openssl", "rustls-0_21"] }
actix-test = { version = "0.1", features = ["openssl", "rustls-0_22"] }
actix-tls = { version = "3.3", features = ["openssl", "rustls-0_22"] }
actix-utils = "3"
actix-web = { version = "4", features = ["openssl"] }
@ -108,11 +122,11 @@ env_logger = "0.10"
flate2 = "1.0.13"
futures-util = { version = "0.3.17", default-features = false }
static_assertions = "1.1"
rcgen = "0.11"
rustls-pemfile = "1"
rcgen = "0.12"
rustls-pemfile = "2"
tokio = { version = "1.24.2", features = ["rt-multi-thread", "macros"] }
zstd = "0.12"
zstd = "0.13"
[[example]]
name = "client"
required-features = ["rustls-0_21"]
required-features = ["rustls-0_22-webpki-roots"]

View File

@ -1,13 +1,17 @@
# awc (Actix Web Client)
# `awc` (Actix Web Client)
> Async HTTP and WebSocket client library.
<!-- prettier-ignore-start -->
[![crates.io](https://img.shields.io/crates/v/awc?label=latest)](https://crates.io/crates/awc)
[![Documentation](https://docs.rs/awc/badge.svg?version=3.2.0)](https://docs.rs/awc/3.2.0)
[![Documentation](https://docs.rs/awc/badge.svg?version=3.4.0)](https://docs.rs/awc/3.4.0)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/awc)
[![Dependency Status](https://deps.rs/crate/awc/3.2.0/status.svg)](https://deps.rs/crate/awc/3.2.0)
[![Dependency Status](https://deps.rs/crate/awc/3.4.0/status.svg)](https://deps.rs/crate/awc/3.4.0)
[![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x)
<!-- prettier-ignore-end -->
## Documentation & Resources
- [API Documentation](https://docs.rs/awc)

View File

@ -1,5 +1,3 @@
#![allow(clippy::uninlined_format_args)]
use std::error::Error as StdError;
#[tokio::main]

Some files were not shown because too many files have changed in this diff Show More