I would like all of my routes to return Json instead of HTML when requested.
For example, when /index.json is requested, it should return the object that the /index html response would be built with.
I'm currently handling this with a "tail match" in the routing macro on line 11:
5 #[derive(Serialize)]
6 struct FollowerPresenter {
7 follower_name: String,
8 followee_name: String,
9 }
10
11 #[get("/index{tail:.*}")]
12 async fn index(
13 mime: web::Path<String>,
14 template: web::Data<tera::Tera>,
15 ) -> Result<HttpResponse, Error> {
16 let presenter = FollowerPresenter {
17 follower_name: "Jill".into(),
18 followee_name: "Jim".into(),
19 };
20
21 match mime.as_str() {
22 "" | "/" => {
23 let body = template
24 .render("index.html", &Context::from_serialize(&presenter).unwrap())
25 .map_err(|_| error::ErrorInternalServerError("Template error"))?;
26
27 Ok(HttpResponse::Ok().content_type("text/html").body(body))
28 }
29 ".json" => Ok(HttpResponse::Ok().json(presenter)),
30 _ => Err(error::ErrorNotFound("Resource Not Found")),
31 }
32 }
33
34 #[actix_web::main]
35 async fn main() -> std::io::Result<()> {
36 HttpServer::new(|| {
37 let tera = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src/views/**/*")).unwrap();
38
39 App::new().data(tera).service(index)
40 })
41 .bind("127.0.0.1:3000")?
42 .run()
43 .await
44 }
There's got to be a way, with middleware or something, to avoid putting the entire control structure on lines 21-30 in each handler.