Commit graph

1040 commits

Author SHA1 Message Date
David Pedersen
4c5068c01f
Add Send + Sync check to all services (#277)
Should prevent us accidentally introducing breaking changes.

Fixes https://github.com/tokio-rs/axum/issues/275
2021-08-26 20:59:55 +02:00
Ken-Miura
e6ca9e4b04
Fix content-type in example response (#276) 2021-08-26 18:16:41 +00:00
David Pedersen
bdc39deef2
Version 0.2.3 (#274)
0.2.3 (26. August, 2021)

- **fixed:** Fix accidental breaking change introduced by internal refactor.
  `BoxRoute` used to be `Sync` but was accidental made `!Sync` ([#273](https://github.com/tokio-rs/axum/pull/273))
2021-08-26 16:22:47 +02:00
David Pedersen
a0be328976
Revert "Remove buffer from BoxRoute (#270)" (#273)
This reverts commit 552d69e5d4.
2021-08-26 14:11:38 +00:00
David Pedersen
7b391d85c8
Version 0.2.2 (#271)
0.2.2 (24. August, 2021)

- **fixed:** Fix URI captures matching empty segments. This means requests with
  URI `/` will no longer be matched by `/:key` ([#264](https://github.com/tokio-rs/axum/pull/264))
- **fixed:** Remove needless trait bounds from `Router::boxed` ([#264](https://github.com/tokio-rs/axum/pull/264))
2021-08-26 06:57:07 +00:00
David Pedersen
552d69e5d4
Remove buffer from BoxRoute (#270)
Boxing a service normally means using `tower::util::BoxService`. That
doesn't implement `Clone` however so normally I had been combining it
with `Buffer` to get that.

But recently I discovered https://github.com/dtolnay/dyn-clone which
makes it possible to clone trait objects. So this adds a new internal
utility called `CloneBoxService` which replaces the previous
`BoxService` + `Buffer` combo in `BoxRoute`.

I'll investigate upstreaming that to tower. I think it makes sense there
since box + clone is quite a common need.
2021-08-26 06:34:53 +00:00
David Pedersen
20f6c3b509
Remove needless traits bounds from Router::boxed (#269)
Turns out these bounds weren't actually needed.

I was hoping it would speed up compile times but that isn't the case.
2021-08-26 08:24:21 +02:00
David Pedersen
0d2db387a8
Fix URI captures matching empty segments (#264)
It was never the intention that `/:key` should match `/`. This fixes
that.

Part of https://github.com/tokio-rs/axum/issues/259
2021-08-24 18:27:06 +00:00
Jonas Platte
ab207af060
Rename .route() / .nest() "description" to "path" (#265) 2021-08-24 19:29:28 +02:00
David Pedersen
9a082a74b0
Version 0.2.1 (#256)
0.2.1 (24. August, 2021)

- **added:** Add `Redirect::to` constructor ([#255](https://github.com/tokio-rs/axum/pull/255))
- **added:** Document how to implement `IntoResponse` for custom error type ([#258](https://github.com/tokio-rs/axum/pull/258))
2021-08-24 12:53:57 +02:00
David Pedersen
3d4ef9dc32
Document how to implement IntoResponse for custom error type (#258)
Fixes https://github.com/tokio-rs/axum/issues/249
2021-08-24 12:42:10 +02:00
Jonas Platte
536b8ca4ec
Add Redirect::to constructor (#255)
The motivation for this is established in the issue it fixes.

Resolves #248
2021-08-24 12:13:18 +02:00
programatik29
1a5f977896
Simplify tls-rustls example (#254)
## Motivation

Current `tls-rustls` example might be inconvenient for some people.

## Solution

Rename current example to `low-level-rustls` and add a high level example in its place.
2021-08-24 09:56:31 +02:00
bear
52ccb1bf42
Update StreamBody doc link (#253) 2021-08-24 07:58:35 +02:00
Eduardo Canellas
1b5359add7
small changes to error handling example (#250) 2021-08-24 07:42:13 +02:00
David Pedersen
02e61dfdd6
Version 0.2.0 (#247)
- Overall:
  - **fixed:** Overall compile time improvements. If you're having issues with compile time
    please file an issue! ([#184](https://github.com/tokio-rs/axum/pull/184)) ([#198](https://github.com/tokio-rs/axum/pull/198)) ([#220](https://github.com/tokio-rs/axum/pull/220))
  - **changed:** Remove `prelude`. Explicit imports are now required ([#195](https://github.com/tokio-rs/axum/pull/195))
- Routing:
  - **added:** Add dedicated `Router` to replace the `RoutingDsl` trait ([#214](https://github.com/tokio-rs/axum/pull/214))
  - **added:** Add `Router::or` for combining routes ([#108](https://github.com/tokio-rs/axum/pull/108))
  - **fixed:** Support matching different HTTP methods for the same route that aren't defined
    together. So `Router::new().route("/", get(...)).route("/", post(...))` now
    accepts both `GET` and `POST`. Previously only `POST` would be accepted ([#224](https://github.com/tokio-rs/axum/pull/224))
  - **fixed:** `get` routes will now also be called for `HEAD` requests but will always have
    the response body removed ([#129](https://github.com/tokio-rs/axum/pull/129))
  - **changed:** Replace `axum::route(...)` with `axum::Router::new().route(...)`. This means
    there is now only one way to create a new router. Same goes for
    `axum::routing::nest`. ([#215](https://github.com/tokio-rs/axum/pull/215))
  - **changed:** Implement `routing::MethodFilter` via [`bitflags`](https://crates.io/crates/bitflags) ([#158](https://github.com/tokio-rs/axum/pull/158))
  - **changed:** Move `handle_error` from `ServiceExt` to `service::OnMethod` ([#160](https://github.com/tokio-rs/axum/pull/160))

  With these changes this app using 0.1:

  ```rust
  use axum::{extract::Extension, prelude::*, routing::BoxRoute, AddExtensionLayer};

  let app = route("/", get(|| async { "hi" }))
      .nest("/api", api_routes())
      .layer(AddExtensionLayer::new(state));

  fn api_routes() -> BoxRoute<Body> {
      route(
          "/users",
          post(|Extension(state): Extension<State>| async { "hi from nested" }),
      )
      .boxed()
  }
  ```

  Becomes this in 0.2:

  ```rust
  use axum::{
      extract::Extension,
      handler::{get, post},
      routing::BoxRoute,
      Router,
  };

  let app = Router::new()
      .route("/", get(|| async { "hi" }))
      .nest("/api", api_routes());

  fn api_routes() -> Router<BoxRoute> {
      Router::new()
          .route(
              "/users",
              post(|Extension(state): Extension<State>| async { "hi from nested" }),
          )
          .boxed()
  }
  ```
- Extractors:
  - **added:** Make `FromRequest` default to being generic over `body::Body` ([#146](https://github.com/tokio-rs/axum/pull/146))
  - **added:** Implement `std::error::Error` for all rejections ([#153](https://github.com/tokio-rs/axum/pull/153))
  - **added:** Add `OriginalUri` for extracting original request URI in nested services ([#197](https://github.com/tokio-rs/axum/pull/197))
  - **added:** Implement `FromRequest` for `http::Extensions` ([#169](https://github.com/tokio-rs/axum/pull/169))
  - **added:** Make `RequestParts::{new, try_into_request}` public so extractors can be used outside axum ([#194](https://github.com/tokio-rs/axum/pull/194))
  - **added:** Implement `FromRequest` for `axum::body::Body` ([#241](https://github.com/tokio-rs/axum/pull/241))
  - **changed:** Removed `extract::UrlParams` and `extract::UrlParamsMap`. Use `extract::Path` instead ([#154](https://github.com/tokio-rs/axum/pull/154))
  - **changed:** `extractor_middleware` now requires `RequestBody: Default` ([#167](https://github.com/tokio-rs/axum/pull/167))
  - **changed:** Convert `RequestAlreadyExtracted` to an enum with each possible error variant ([#167](https://github.com/tokio-rs/axum/pull/167))
  - **changed:** `extract::BodyStream` is no longer generic over the request body ([#234](https://github.com/tokio-rs/axum/pull/234))
  - **changed:** `extract::Body` has been renamed to `extract::RawBody` to avoid conflicting with `body::Body` ([#233](https://github.com/tokio-rs/axum/pull/233))
  - **changed:** `RequestParts` changes ([#153](https://github.com/tokio-rs/axum/pull/153))
      - `method` new returns an `&http::Method`
      - `method_mut` new returns an `&mut http::Method`
      - `take_method` has been removed
      - `uri` new returns an `&http::Uri`
      - `uri_mut` new returns an `&mut http::Uri`
      - `take_uri` has been removed
  - **changed:** Remove several rejection types that were no longer used ([#153](https://github.com/tokio-rs/axum/pull/153)) ([#154](https://github.com/tokio-rs/axum/pull/154))
- Responses:
  - **added:** Add `Headers` for easily customizing headers on a response ([#193](https://github.com/tokio-rs/axum/pull/193))
  - **added:** Add `Redirect` response ([#192](https://github.com/tokio-rs/axum/pull/192))
  - **added:** Add `body::StreamBody` for easily responding with a stream of byte chunks ([#237](https://github.com/tokio-rs/axum/pull/237))
  - **changed:** Add associated `Body` and `BodyError` types to `IntoResponse`. This is
    required for returning responses with bodies other than `hyper::Body` from
    handlers. See the docs for advice on how to implement `IntoResponse` ([#86](https://github.com/tokio-rs/axum/pull/86))
  - **changed:** `tower::util::Either` no longer implements `IntoResponse` ([#229](https://github.com/tokio-rs/axum/pull/229))

  This `IntoResponse` from 0.1:
  ```rust
  use axum::{http::Response, prelude::*, response::IntoResponse};

  struct MyResponse;

  impl IntoResponse for MyResponse {
      fn into_response(self) -> Response<Body> {
          Response::new(Body::empty())
      }
  }
  ```

  Becomes this in 0.2:
  ```rust
  use axum::{body::Body, http::Response, response::IntoResponse};

  struct MyResponse;

  impl IntoResponse for MyResponse {
      type Body = Body;
      type BodyError = <Self::Body as axum::body::HttpBody>::Error;

      fn into_response(self) -> Response<Self::Body> {
          Response::new(Body::empty())
      }
  }
  ```
- SSE:
  - **added:** Add `response::sse::Sse`. This implements SSE using a response rather than a service ([#98](https://github.com/tokio-rs/axum/pull/98))
  - **changed:** Remove `axum::sse`. Its been replaced by `axum::response::sse` ([#98](https://github.com/tokio-rs/axum/pull/98))

  Handler using SSE in 0.1:
  ```rust
  use axum::{
      prelude::*,
      sse::{sse, Event},
  };
  use std::convert::Infallible;

  let app = route(
      "/",
      sse(|| async {
          let stream = futures::stream::iter(vec![Ok::<_, Infallible>(
              Event::default().data("hi there!"),
          )]);
          Ok::<_, Infallible>(stream)
      }),
  );
  ```

  Becomes this in 0.2:

  ```rust
  use axum::{
      handler::get,
      response::sse::{Event, Sse},
      Router,
  };
  use std::convert::Infallible;

  let app = Router::new().route(
      "/",
      get(|| async {
          let stream = futures::stream::iter(vec![Ok::<_, Infallible>(
              Event::default().data("hi there!"),
          )]);
          Sse::new(stream)
      }),
  );
  ```
- WebSockets:
  - **changed:** Change WebSocket API to use an extractor plus a response ([#121](https://github.com/tokio-rs/axum/pull/121))
  - **changed:** Make WebSocket `Message` an enum ([#116](https://github.com/tokio-rs/axum/pull/116))
  - **changed:** `WebSocket` now uses `Error` as its error type ([#150](https://github.com/tokio-rs/axum/pull/150))

  Handler using WebSockets in 0.1:

  ```rust
  use axum::{
      prelude::*,
      ws::{ws, WebSocket},
  };

  let app = route(
      "/",
      ws(|socket: WebSocket| async move {
          // do stuff with socket
      }),
  );
  ```

  Becomes this in 0.2:

  ```rust
  use axum::{
      extract::ws::{WebSocket, WebSocketUpgrade},
      handler::get,
      Router,
  };

  let app = Router::new().route(
      "/",
      get(|ws: WebSocketUpgrade| async move {
          ws.on_upgrade(|socket: WebSocket| async move {
              // do stuff with socket
          })
      }),
  );
  ```
- Misc
  - **added:** Add default feature `tower-log` which exposes `tower`'s `log` feature. ([#218](https://github.com/tokio-rs/axum/pull/218))
  - **changed:** Replace `body::BoxStdError` with `axum::Error`, which supports downcasting ([#150](https://github.com/tokio-rs/axum/pull/150))
  - **changed:** `EmptyRouter` now requires the response body to implement `Send + Sync + 'static'` ([#108](https://github.com/tokio-rs/axum/pull/108))
  - **changed:** `Router::check_infallible` now returns a `CheckInfallible` service. This
    is to improve compile times ([#198](https://github.com/tokio-rs/axum/pull/198))
  - **changed:** `Router::into_make_service` now returns `routing::IntoMakeService` rather than
    `tower::make::Shared` ([#229](https://github.com/tokio-rs/axum/pull/229))
  - **changed:** All usage of `tower::BoxError` has been replaced with `axum::BoxError` ([#229](https://github.com/tokio-rs/axum/pull/229))
  - **changed:** Several response future types have been moved into dedicated
    `future` modules ([#133](https://github.com/tokio-rs/axum/pull/133))
  - **changed:** `EmptyRouter`, `ExtractorMiddleware`, `ExtractorMiddlewareLayer`,
    and `QueryStringMissing` no longer implement `Copy` ([#132](https://github.com/tokio-rs/axum/pull/132))
  - **changed:** `service::OnMethod`, `handler::OnMethod`, and `routing::Nested` have new response future types ([#157](https://github.com/tokio-rs/axum/pull/157))
2021-08-23 20:49:29 +02:00
David Pedersen
c2bfaf26d8 Removing prelude is a "changed" not a "fixed" 2021-08-23 18:42:51 +02:00
David Pedersen
0ab6ea6b6a Mention tower-log feature in docs 2021-08-23 18:40:18 +02:00
David Pedersen
cb6f5b95b3 Minor reordering of changelog 2021-08-23 18:40:07 +02:00
David Pedersen
d006b4f6f7 Remove notice about breaking changes in 0.2 from readme 2021-08-23 18:36:34 +02:00
David Pedersen
77f7b51d2f Update readme example to 0.2 2021-08-23 18:36:11 +02:00
David Pedersen
c8c8e6509b
Add upgrade examples to the changelog (#245)
Shows how to upgrade

- General routing
- SSE
- WebSockets
2021-08-23 18:24:08 +02:00
David Pedersen
6777dc1e5c
Add constructor to Sse (#244)
I think this is more consistent with the rest of the API
2021-08-23 17:51:30 +02:00
David Pedersen
a753eac23f
Remove boxing from StreamBody (#241)
I just had a thought: Why should `response::Headers` be generic, but
`body::StreamBody` should not? `StreamBody` previously boxed the stream
to erase the generics. So we had `response::Headers<T>` but
`body::StreamBody`, without generics.

After thinking about it I think it actually makes sense for responses to
remain generic because you're able to use `impl IntoResponse` so you
don't have to name the generics.

Whereas in the case of `BodyStream` (an extractor) you cannot use `impl Trait`
so it makes sense to box the inner body to make the type easier to name. Besides,
`BodyStream` is mostly useful when the request body isn't `hyper::Body`, as
that already implements `Stream`.
2021-08-22 22:03:56 +02:00
David Pedersen
b75c34b821 Fix typo 2021-08-22 16:12:05 +02:00
David Pedersen
dbab5a84b4
Expand middleware docs (#239)
Adds docs on
- Commonly used middleware
- Writing your own middleware
- Links to tower's guides
2021-08-22 15:56:56 +02:00
David Pedersen
2322d39800
Add StreamBody (#237)
This adds `StreamBody` which converts a `Stream` of `Bytes` into a `http_body::Body`.

---

As suggested by Kestrer on Discord it would make sense for axum to provide different kinds of body types other than `Empty`, `Full`, and `hyper::Body`. There is also some talk about [splitting up `hyper::Body`](https://github.com/hyperium/hyper/issues/2345) so this can be seen as getting started on that effort. axum's body types could be moved to hyper or http-body if thats the direction we decide on.

The types I'm thinking about adding are:

- `StreamBody`-  added in this PR
- `AsyncReadBody` - similar to [http-body#41](https://github.com/hyperium/http-body/pull/41/files)
- `ChannelBody` - similar to `hyper::Body::channel`
2021-08-22 14:41:51 +02:00
David Pedersen
5ae94b6a24
Group items in changelog differently (#238) 2021-08-22 14:38:59 +02:00
David Pedersen
80a8355eff
Remove generic parameter from BodyStream (#234)
I think `BodyStream` is more useful without being generic over the
request body.

I'm also looking into adding a response body from a stream called
`StreamBody` which will work pretty much opposite to this.
2021-08-22 11:33:38 +02:00
David Pedersen
add3dc36f9
Rename extract::Body to extract::RawBody (#233) 2021-08-21 20:04:39 +02:00
David Pedersen
fbd43c6600
Document not being able to mix fallible and infallible routes (#232)
I haven't been able to find a proper solution for #89 so for now I think
we should document the issue and move on with shipping 0.2.

Part of https://github.com/tokio-rs/axum/issues/89
2021-08-21 15:36:50 +02:00
David Pedersen
8a61b9ffe1
Use std::future::ready (#231)
`std::future::ready` has been stable since 1.48 so since axum's MSRV is
1.51 we can use this rather the one from `futures_util`.
2021-08-21 15:18:05 +02:00
David Pedersen
82dc847d47
Fix nest docs inconsistency (#230) 2021-08-21 15:06:15 +02:00
David Pedersen
f8a0d81d79
Remove tower from axum's public API (#229)
Instead rely on `tower-service` and `tower-layer`. `tower` itself is
only used internally.

Fixes https://github.com/tokio-rs/axum/issues/186
2021-08-21 15:01:30 +02:00
David Pedersen
35ea7ca0ff
Mention using Path<HashMap> to capture all params (#228)
Might not be entirely obvious that you can do this so makes sense to
mention in the docs.
2021-08-21 14:21:31 +02:00
David Pedersen
2bbf6105d0
Fix 404 example (#226)
Forgot to actually set the correct status code
2021-08-21 12:02:50 +02:00
David Pedersen
66a806630c Note changes to examples in 0.2 2021-08-21 11:35:57 +02:00
David Pedersen
08544f9d92 Reorganize changelog a bit 2021-08-21 11:35:49 +02:00
David Pedersen
0d8f8b7b6c
Fallback to calling next route if no methods match (#224)
This removes a small foot gun from the routing.

This means matching different HTTP methods for the same route that
aren't defined together now works.

So `Router::new().route("/", get(...)).route("/", post(...))` now
accepts both `GET` and `POST`. Previously only `POST` would be accepted.
2021-08-21 01:00:12 +02:00
David Pedersen
971c0a394a
Revert "Simplify handler trait (#221)" (#223)
This reverts commit 44c58bdf5f.
2021-08-20 23:56:16 +02:00
David Pedersen
f984198440
Add more examples to "Building responses" section (#222)
Someone on reddit suggested adding more examples.
2021-08-20 20:50:11 +02:00
David Pedersen
44c58bdf5f
Simplify handler trait (#221)
Rely on the `impl FromRequest for (T, ...)` rather than extracting things directly inside the macro.
2021-08-20 20:36:34 +02:00
David Pedersen
e8bc3f5082
Further compile time improvements (#220)
This improves compiles further when using lots of nested routes. Such as
the example posted
[here](https://github.com/tokio-rs/axum/issues/200#issuecomment-902541073).

It seems rustc is really slow at checking bounds on these kinds of
intermediate builder methods. Should probably file an issue about that.
2021-08-20 19:51:29 +02:00
Johannes Becker
be61b8c611
Update changelog (#219) 2021-08-20 17:23:44 +02:00
Johannes Becker
7350b817b0
expose tower log feature (#218) 2021-08-20 13:41:28 +02:00
David Pedersen
39a0c26795
Add print-request-response example (#216)
* Add `print-request-response` example

Someone asked about this on Discord. I think its worth adding as an
example.

* add missing feature
2021-08-20 09:26:31 +02:00
David Pedersen
1bda638c6b Simplify 404 example using or 2021-08-19 22:50:42 +02:00
David Pedersen
23dcf3631e Export Or in a more consistent way 2021-08-19 22:44:26 +02:00
David Pedersen
570e13195c Inline Router in root module docs 2021-08-19 22:39:37 +02:00
David Pedersen
ca4d9a2bb9
Replace route with Router::new().route() (#215)
This way there is now only one way to create a router:

```rust
use axum::{Router, handler::get};

let app = Router::new()
    .route("/foo", get(handler))
    .route("/foo", get(handler));
```

`nest` was changed in the same way:

```rust
use axum::Router;

let app = Router::new().nest("/foo", service);
```
2021-08-19 22:37:48 +02:00