axum crate の Handler
前回は axum crate の Router::merge と Router::nest について書きました。
今回は axum crate の Handler について書きます。
今回も axum crate のバージョンは 0.8.6 です。
Handler とは何か?
axum crate における Handler は 0 個以上の Extractor を引数に取り、 IntoResponse trait の実装を返す、非同期関数です。リクエストを handle するものです。
前回までに書いてきた Router は、あるパス・メソッドを Handler に振り分けるものでした。
Handler の使い方
かんたんな Handler の使い方を見ます。 handler mod のドキュメントから例 (一部改変) を取り上げます。
https://docs.rs/axum/0.8.6/axum/handler/index.html
// Handler that immediately returns an empty `200 OK` response.
async fn unit_handler() {}
// Handler that immediately returns a `200 OK` response with a plain text
// body.
async fn string_handler() -> String {
"Hello, World!".to_string()
}
// Handler that buffers the request body and returns it.
//
// This works because `Bytes` implements `FromRequest`
// and therefore can be used as an extractor.
//
// `String` and `StatusCode` both implement `IntoResponse` and
// therefore `Result<String, StatusCode>` also implements `IntoResponse`
async fn echo(body: axum::body::Bytes) -> Result<String, axum::http::StatusCode> {
if let Ok(string) = String::from_utf8(body.to_vec()) {
Ok(string)
} else {
Err(axum::http::StatusCode::BAD_REQUEST)
}
}
引数も戻り値もない (() を返す) 場合は 200 OK 扱いになるようです。 () は IntoResponse trait を実装しています。
引数がなく、文字列を返す場合は 200 OK で plain text として文字列を返すようです。文字列 (String) は IntoResponse trait を実装しているので、これで良いわけです。
最後は引数に axum::body::Bytes を取り、 Result<String, StatusCode> を返す場合です。コメントにあるとおり axum::body::Bytes は FromRequest を実装しており Extractor です。こちらもコメントにあるとおり Result<impl IntoResponse, impl IntoResponse> は IntoResponse を実装していますし、 String も IntoResponse を実装していますし、 StatusCode も IntoResponse を実装しており、戻り値も IntoResponse になっています。
これらの例と説明から分かるとおり IntoResponse さえ実装していれば Result<T, E> でもいいので、独自のエラー型も ? も使えます。
Handler のルール
おおまかに Handler がどのようなものか分かったところで、もうすこし詳しく調べていきます。
ドキュメントには Handler になるためのルールが書いてあります。
https://docs.rs/axum/0.8.6/axum/handler/index.html#debugging-handler-type-errors
- Are async fns.
- Take no more than 16 arguments that all implement Send.
- All except the last argument implement FromRequestParts.
- The last argument implements FromRequest.
- Returns something that implements IntoResponse.
- If a closure is used it must implement Clone + Send and be 'static.
- Returns a future that is Send. The most common way to accidentally make a future !Send is to hold a !Send type across an await.
使ってみると分かるのですが、 Handler でなくなってしまうことがままあります。そのときのエラーメッセージが「 Handler trait が実装されていない」という旨のものになってしまい、分かりづらいです。
その問題の解決のために axum-macros crate の debug_handler proc macro の紹介もされているのですが、ぼくはこれで「助かった!」となったことがないです……。
Handler trait
改めてですが、 Handler は Handler trait として表現されています。
先のルールは Handler trait やそのブランケット実装をどうしているのかを示したものです。かんたんな Handler の使い方で挙げた関数も Handler trait のブランケット実装が提供されているので Handler として使用できるわけですね。
Handler trait を見ていきます。
https://docs.rs/axum/0.8.6/axum/handler/trait.Handler.html
pub trait Handler<T, S>:
Clone
+ Send
+ Sync
+ Sized
+ 'static {
type Future: Future<Output = Response> + Send + 'static;
// Required method
fn call(self, req: Request, state: S) -> Self::Future;
// Provided methods
fn layer<L>(self, layer: L) -> Layered<L, Self, T, S>
where L: Layer<HandlerService<Self, T, S>> + Clone,
L::Service: Service<Request> { ... }
fn with_state(self, state: S) -> HandlerService<Self, T, S> { ... }
}
call はいわゆる呼び出しですね。
layer は Handler に layer を適用できます。これはまた Middleware を見るときに出てきそうです。
with_state は State を設定して Service にするものですね。 HandlerWithoutStateExt::into_service でも Service にすることはできそうです。
Handler には layer で middleware が設定できるわけですね。ぼくは一度 Service や Router に追加しないといけないものと思い込んでいました。
関数でない Handler
Handler trait のドキュメントには他にも面白いことが書いてあります。
https://docs.rs/axum/0.8.6/axum/handler/trait.Handler.html#handlers-that-arent-functions
T: IntoResponse にも Handler が実装されているということです。これは通常レスポンスとして返すような値それ自身も Handler ということです。
"Hello, World!" のような文字列も、 StatusCode::CREATED みたいなものも Handler なんですね。
おわりに
Handler の概要やかんたんな例を調べてみました。
次回は Handler の実装をもうすこし追いかけてみようと思います。
Discussion