由于任务是分发图片,所以我遵循以下指南:
https://actix.rs/docs/static-files/
例如,我static
在项目中创建了一个目录( )并上传了1张图片到其中:
接下来,我编写以下代码:(
只注意带有注释的行(只有两行)// Взято из гайда
:)
use actix_cors::Cors;
use actix_web::{http, web, get, post, App, HttpResponse, HttpServer, Result};
use serde::{Deserialize, Serialize};
use actix_files::Files; // Взято из гайда
#[derive(Serialize, Deserialize)]
struct MyObj {
name: String,
}
#[derive(Serialize, Deserialize, Clone)]
struct MyParams {
foo: Option<String>,
}
#[derive(Serialize, Deserialize)]
struct MyResponseObj {
name: String,
params: MyParams,
}
#[get("/{name}")]
async fn index_get(path: web::Path<MyObj>, params: web::Query<MyParams>) -> Result<HttpResponse> {
Ok(HttpResponse::Ok().json(MyResponseObj {
name: path.name.to_string(),
params: params.clone(),
}))
}
#[post("/{name}")]
async fn index_post(path: web::Path<MyObj>, params: web::Json<MyParams>) -> Result<HttpResponse> {
hello().await;
println!("{:?}", params.foo);
println!("{:?}", path.name);
Ok(HttpResponse::Ok().json(MyResponseObj {
name: path.name.to_string(),
params: params.clone(),
}))
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new()
.wrap(
Cors::new() // <- Construct CORS middleware builder
.allowed_origin("http://localhost:3000")
.allowed_methods(vec!["GET", "POST"])
.allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
.allowed_header(http::header::CONTENT_TYPE)
.max_age(3600)
.finish())
.service(Files::new("/static", ".")) // Взято из гайда
.service(index_get)
.service(index_post)
)
.bind("127.0.0.1:8088")?
.run()
.await
}
货运.toml
[package]
name = "hello_world"
version = "0.1.0"
authors = ["Mike_Kharkov <yamaradg@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix-web = "3.0.1"
actix-rt = "1.1.1"
actix-cors = "0.3.0"
actix-files = "0.3.0"
postgres = "0.17.5"
serde = { version = "1.0.116", features = ["derive"] }
serde_json = "1.0"
json = "0.12"
tokio-postgres = "0.5.5"
tokio = "0.2.22"
env_logger = "0.7.1"
Files::new("/static", ".")
指定静态目录的绝对路径而不是点。例如,您可以这样做: