cannot call async method in route #915
Answered
by
davidpdrsn
thinkingInWorldByNull
asked this question in
Q&A
-
Bug ReportVersion
PlatformDarwin 16-MacBookPro 21.4.0 Darwin Kernel Version 21.4.0: Fri Mar 18 00:46:32 PDT 2022; root:xnu-8020.101.4~15/RELEASE_ARM64_T6000 arm64 DescriptionCannot call async method in handle. code example as follow.
#[derive(Serialize, Deserialize, Debug)]
struct Param{
spec:String,
origin_url: String,
}
type Cache = Arc<Mutex<LruCache<u64, Bytes>>>;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
let cache:Cache = Arc::new(Mutex::new(LruCache::new(1024)));
let app = Router::new()
.route("/image/:spec/:origin_url", get(handler))
.layer(ServiceBuilder::new().layer(AddExtensionLayer::new(cache)));
let addr = SocketAddr::from(([127, 0, 0, 1], 13000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
info!("start ok listener on 13000");
}
async fn handler(Path(Param{spec, origin_url}):Path<Param>, Extension(cache):Extension<Cache>) -> Result<Bytes, StatusCode>{
let image_bytes = get_image_byte(origin_url.borrow(), cache).await
.map_err(|_|StatusCode::BAD_REQUEST)?;
Err(StatusCode::NOT_FOUND)
}
#[instrument(level = "info", skip(cache))]
async fn get_image_byte(origin_url:&str, cache: Cache) -> Result<Bytes> {
let mut hasher = DefaultHasher::new();
hasher.write(origin_url.as_bytes());
let url_hash = hasher.finish();
let g = &mut cache.lock().unwrap();
let data = match g.get(&url_hash) {
Some(v) => {
info!("get from cache{}", url_hash);
v.to_owned()
}
None => {
info!("fetch image it");
//❓open this will case " the trait `Handler<_, _>` is not implemented for ..."
async_method().await?
//❗️but block method is ok
// block_method()?
}
};
Ok(data)
}
fn block_method() -> Result<Bytes>{
Ok(Bytes::from("123"))
}
async fn async_method() -> Result<Bytes>{
Ok(Bytes::from("123"))
} |
Beta Was this translation helpful? Give feedback.
Answered by
davidpdrsn
Apr 7, 2022
Replies: 1 comment 3 replies
-
What is the compile error 👀 ? If its something with |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
davidpdrsn
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is the compile error 👀 ?
If its something with
Handler
not being implemented have a look at https://docs.rs/axum/latest/axum/handler/index.html#debugging-handler-type-errors