Rust:axum学习笔记(5) 处理静态资源
接上一篇继续,静态资源比如css/js/jpg等,一般不需要服务端做额外的业务处理,直接透传给浏览器就行,axum可以指定将某个目录指定为静态资源,参考下面的代码:
let app = Router::new() .nest( "/static", get_service(ServeDir::new(".")).handle_error(|error: std::io::Error| async move { ( StatusCode::INTERNAL_SERVER_ERROR, format!("Unhandled internal error: {}", error), ) }), )
这一段的意思是将当前目录设置为静态资源目录,用/static访问,当然这个.也可以换成绝对路径。
假设项目的结构如上,要访问static_file/src/main.rs,直接用http://localhost:3000/static/static_file/src/main.rs 访问,效果如下:
最后附加上完整代码:
cargo.toml
[package] name = "static_file" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] axum = {version = "0.4.3", features = ["headers"] } tokio = { version = "1.0", features = ["full"] } tracing = "0.1" tracing-subscriber = { version="0.3", features = ["env-filter"] } tower-http = { version = "0.2.0", features = ["fs", "trace"] }
main.rs
use axum::{http::StatusCode, routing::{get_service,get}, Router}; use std::net::SocketAddr; use tower_http::{services::ServeDir, trace::TraceLayer}; #[tokio::main] async fn main() { // Set the RUST_LOG, if it hasn't been explicitly defined if std::env::var_os("RUST_LOG").is_none() { std::env::set_var( "RUST_LOG", "example_static_file_server=debug,tower_http=debug", ) } tracing_subscriber::fmt::init(); let app = Router::new() .nest( "/static", get_service(ServeDir::new(".")).handle_error(|error: std::io::Error| async move { ( StatusCode::INTERNAL_SERVER_ERROR, format!("Unhandled internal error: {}", error), ) }), ) .route("/", get(|| async { "Hello, World!" })) .layer(TraceLayer::new_for_http()); let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); tracing::debug!("listening on {}", addr); axum::Server::bind(&addr) .serve(app.into_make_service()) .await .unwrap(); }
作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。