Sam*_*sel 6 app-data rust rust-actix actix-web
我正在使用 Actix 框架来创建一个简单的服务器,并且我已经使用一个简单的 HTML 前端实现了文件上传。
use actix_web::web::Data;
use actix_web::{middleware, web, App, HttpResponse, HttpServer};
use std::cell::Cell;
// file upload functions, the same as you can find it under the
// actix web documentation:
// https://github.com/actix/examples/blob/master/multipart/src/main.rs :
mod upload;
fn index() -> HttpResponse {
let html = r#"<html>
<head><title>Upload Test</title></head>
<body>
<form target="/" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="Submit"></button>
</form>
</body>
</html>"#;
HttpResponse::Ok().body(html)
}
#[derive(Clone)]
pub struct AppState {
counter: Cell<usize>,
}
impl AppState {
fn new() -> Result<Self, Error> {
// some stuff
Ok(AppState {
counter: Cell::new(0usize),
})
}
}
fn main() {
let app_state = AppState::new().unwrap();
println!("Started http server: http://127.0.0.1:8000");
HttpServer::new(move || {
App::new()
.wrap(middleware::Logger::default())
.service(
web::resource("/")
.route(web::get().to(index))
.route(web::post().to_async(upload::upload)),
)
.data(app_state.clone())
})
.bind("127.0.0.1:8000")
.unwrap()
.run()
.unwrap();
}
Run Code Online (Sandbox Code Playgroud)
运行服务器工作正常,但是当我提交文件上传时,它说:
应用数据未配置,配置使用 App::data()
我不知道该怎么办。
小智 4
我请 rust-jp 社区的人告诉你正确的答案。
\n\n使用Arc外HttpServer.
/*\n~~~Cargo.toml\n[package]\nname = "actix-data-example"\nversion = "0.1.0"\nauthors = ["ncaq <ncaq@ncaq.net>"]\nedition = "2018"\n\n[dependencies]\nactix-web = "1.0.0-rc"\nenv_logger = "0.6.0"\n~~~\n */\n\nuse actix_web::*;\nuse std::sync::*;\n\nfn main() -> std::io::Result<()> {\n std::env::set_var("RUST_LOG", "actix_web=trace");\n env_logger::init();\n\n let data = Arc::new(Mutex::new(ActixData::default()));\n HttpServer::new(move || {\n App::new()\n .wrap(middleware::Logger::default())\n .data(data.clone())\n .service(web::resource("/index/").route(web::get().to(index)))\n .service(web::resource("/create/").route(web::get().to(create)))\n })\n .bind("0.0.0.0:3000")?\n .run()\n}\n\nfn index(actix_data: web::Data<Arc<Mutex<ActixData>>>) -> HttpResponse {\n println!("actix_data: {:?}", actix_data);\n HttpResponse::Ok().body(format!("{:?}", actix_data))\n}\n\nfn create(actix_data: web::Data<Arc<Mutex<ActixData>>>) -> HttpResponse {\n println!("actix_data: {:?}", actix_data);\n actix_data.lock().unwrap().counter += 1;\n HttpResponse::Ok().body(format!("{:?}", actix_data))\n}\n\n/// actix-web\xe3\x81\x8c\xe4\xbf\x9d\xe6\x8c\x81\xe3\x81\x99\xe3\x82\x8b\xe7\x8a\xb6\xe6\x85\x8b\n#[derive(Debug, Default)]\nstruct ActixData {\n counter: usize,\n}\nRun Code Online (Sandbox Code Playgroud)\n\n\n
| 归档时间: |
|
| 查看次数: |
2833 次 |
| 最近记录: |