Return CSS, JavaScript, JSON, and plain-text From axum in Rust
``cargo
[dependencies]
axum = "0.8.1"
axum-extra = "0.10.0"
http = "1.2.0"
tokio = { version = "1", features = ["full"] }
```
use axum::http::header;
use axum::response::Html;
use axum::response::IntoResponse;
use axum::Json;
use axum::{routing::get, Router};
use axum_extra::response::Css;
use axum_extra::response::JavaScript;
use http::StatusCode;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(return_html))
.route("/example.css", get(return_css))
.route("/example.js", get(return_js))
.route("/example.json", get(return_json))
.route("/example.txt", get(return_plain_text));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3366").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn return_css() -> impl IntoResponse {
Css::from("body {background: black;}")
}
async fn return_html() -> impl IntoResponse {
Html("this is html".to_string())
}
async fn return_json() -> impl IntoResponse {
Json("{}".to_string())
}
async fn return_js() -> impl IntoResponse {
JavaScript::from("console.log(`here`);")
}
async fn return_plain_text() -> impl IntoResponse {
(
StatusCode::OK,
[(header::CONTENT_TYPE, "text/plain")],
"foo",
)
}