当前位置: 首页 > 工具软件 > Tokio-axum > 使用案例 >

Rust axum开发web服务1

童宏富
2023-12-01

Rust axum开发web服务

组件依赖:

[dependencies]
axum = { version = "0.6.6", features = ["multipart"] }
axum-sessions = "0.4.1"
futures = "0.3.25"
tokio = { version = "1.21.2", features = ["full"] }
tokio-util = { version = "0.7.4", features = ["io"] }
rust-s3 = "0.32.3"
log = "0.4.17"
env_logger = "0.10.0"

Server代码

#[tokio::main]
async fn main() {
    init_logging(LevelFilter::Info);
    
    let store = async_session::MemoryStore::new();
    let secret = rand::thread_rng().gen::<[u8; 128]>();
    let session_layer = SessionLayer::new(store, &secret)
                                                        .with_secure(false)
                                                        .with_cookie_name(COOKIE_VALUE)
                                                        .with_cookie_path("cookies")
                                                        .with_persistence_policy(PersistencePolicy::Always)
                                                        .with_session_ttl(Some(Duration::from_secs(60 * 60 * 24 * 30)));
	//跨域配置
    let cors = CorsLayer::new()
        .allow_headers(Any)
        .allow_origin(Any);
    let router = Router::new()
        .route("/", get(|| async {"Hello World!!"}))
        .route("/api", get(api_msg))
        .layer(session_layer)
        .layer(cors.clone())
        ;
        

    let addr = SocketAddr::from(([127, 0, 0, 1], 8081));
    tokio::spawn(sched_work());  //调用异步轮询接口
    
    axum::Server::bind(&addr)
        .serve(router.into_make_service())
        .await
        .unwrap();

    
}

handler:

pub async fn api_msg() -> Response {
    let data = "各种形式数据";
    let resp = Json(OrdResponse{
        code: 200,
        data: data,
    });
    info!("resp: {:?}", resp);
    resp.into_response()
}

响应struct:

#[derive(Serialize, Deserialize, Debug)]
pub struct BalanceInfo {
    pub cardinal: usize,
}
 类似资料: