[英]actix-web app_data is always None in request handler
I want to register application level data when configuring Actix http server, but when I try to access the data in a request handler with HttpRequest::app_data()
I always get None
.我想在配置 Actix http 服务器时注册应用程序级数据,但是当我尝试使用
HttpRequest::app_data()
访问请求处理程序中的数据时,我总是得到None
。 The code below panics in the index
request handler at the expect
statement.下面的代码在
expect
语句的index
请求处理程序中发生恐慌。 It does work however if I use a String
instead of my TestData
struct.但是,如果我使用
String
而不是我的TestData
结构,它确实有效。
What am I doing wrong?我究竟做错了什么?
use actix_web::{middleware, web, HttpRequest, Result, Responder, HttpResponse};
use actix_web::{App, HttpServer};
use std::sync::Arc;
#[macro_use]
extern crate log;
extern crate env_logger;
struct TestData {
host: String
}
pub async fn index(req: HttpRequest) -> impl Responder {
let td: &TestData = req.app_data().expect("Test data missing in request handler.");
td.host.clone()
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG",
format!("actix_server={log_level},actix_web={log_level}",
log_level="DEBUG"));
env_logger::init();
let server_data = web::Data::new(
TestData {
host: "Dadada".to_string(),
}
);
HttpServer::new(move || {
App::new()
.app_data(server_data.clone())
.route("/", web::get().to(index))
.wrap(middleware::Logger::default())
})
.bind("127.0.0.1:8080")?
.run()
.await
}
You need to specify the Data<T>
type to app_data
with turbo fish syntax.您需要使用 turbo fish 语法为
app_data
指定Data<T>
类型。
pub async fn index(req: HttpRequest) -> impl Responder {
let td: &TestData = req.app_data::<web::Data<TestData>>().expect("Test data missing in request handler.");
td.host.clone()
}
If you take a look to HttpRequest::app_data
defintion, you see that app_data
needs this info to desambiguate the get
call如果您查看
HttpRequest::app_data
定义,您会看到app_data
需要此信息来消除get
调用的歧义
pub fn app_data<T: 'static>(&self) -> Option<&T> {
for container in self.0.app_data.iter().rev() {
//Used here ------------------------\/
if let Some(data) = container.get::<T>() {
return Some(data);
}
}
None
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.