LoginSignup
7
0

RustのAxum(POST)でボディを受け取ろうとするとtraitエラーが発生する

Posted at

はじめに

Axumでボディを受け取って処理をするPOSTのAPIを作成したところかなり解決に時間がかかったのでまとめます。
ちなみに根本的原因はわからないので詳しい方はコメントをいただきたいです。

問題

POSTのAPIを一つ作りました
ここではPOSTされたボディをJsonで受け取るようになっています

router.rs
async fn post_todo(
    Json(payload): Json<SearchCondition>,
    Extension(container): Extension<Arc<Container>>,
) -> impl IntoResponse {

しかし以下のエラーが発生してしまいます

the trait bound `fn(Json<SearchCondition>, Extension<Arc<Container>>, HeaderMap) -> impl Future<Output = impl IntoResponse> {post_v2_news}: Handler<_, _, _>` is not satisfied
the following other types implement trait `Handler<T, S, B>`:
  <Or<L, R, Lt, Rt, S, B> as Handler<(M, Lt, Rt), S, B>>
  <IntoHandler<H, T, S, B> as Handler<T, S, B>>
  <Layered<L, H, T, S, B, B2> as Handler<T, S, B2>>
  <MethodRouter<S, B> as Handler<(), S, B>>rustc
the trait bound `fn(axum::Json<SearchCondition>, Extension<Arc<Container>>, HeaderMap) -> impl Future<Output = impl IntoResponse> {post_v2_news}: Handler<_, _, _>` is not satisfied
the following other types implement trait `Handler<T, S, B>`:
  <Or<L, R, Lt, Rt, S, B> as Handler<(M, Lt, Rt), S, B>>
  <IntoHandler<H, T, S, B> as Handler<T, S, B>>
  <Layered<L, H, T, S, B, B2> as Handler<T, S, B2>>
  <MethodRouter<S, B> as Handler<(), S, B>>rustc

JSONAxumから利用しているので謎でした

解決方法

以下で解決ができました

router.rs
async fn post_todo(
    Extension(container): Extension<Arc<Container>>,
    Json(payload): Json<SearchCondition>,
) -> impl IntoResponse {

引数のボディの受け取りの順序を変更したところうまくうごくようになりました
基本的にハンドラーは引数の順序に依存がないようにできているはずなのですが、なぜか依存が生まれていて起きているようでした

おわりに

インターンできてくれたRust1日目の方がまさかの解決してくれて驚きました
プログラミングにもビギナーズラックがあるんですかね

それにしてもこの挙動は困ります。よくありそうなパターンだと思うので

7
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
0