git_http_backend/actix/
get_text_file.rs

1use crate::GitConfig;
2use actix_files::NamedFile;
3use actix_web::http::header;
4use actix_web::http::header::HeaderValue;
5use actix_web::{web, HttpRequest, HttpResponse, Responder};
6use std::collections::HashMap;
7
8pub async fn get_text_file(
9    request: HttpRequest,
10    service: web::Data<impl GitConfig>,
11) -> impl Responder {
12    let uri = request.uri();
13    let path = uri.path().to_string();
14    let path = service.rewrite(path).await;
15    let mut resp = HashMap::new();
16    resp.insert("Pragma".to_string(), "no-cache".to_string());
17    resp.insert(
18        "Cache-Control".to_string(),
19        "no-cache, max-age=0, must-revalidate".to_string(),
20    );
21    resp.insert(
22        "Expires".to_string(),
23        "Fri, 01 Jan 1980 00:00:00 GMT".to_string(),
24    );
25    if !path.exists() {
26        return HttpResponse::NotFound().body("File not found");
27    }
28    match NamedFile::open(path) {
29        Ok(mut named_file) => {
30            named_file = named_file.use_last_modified(true);
31            let mut response = named_file.into_response(&request);
32            for (k, v) in resp.iter() {
33                response.headers_mut().insert(
34                    k.to_string().parse().unwrap(),
35                    HeaderValue::from_str(v).unwrap(),
36                );
37            }
38
39            response.headers_mut().insert(
40                header::CONTENT_TYPE,
41                HeaderValue::from_str("text/plain").unwrap(),
42            );
43            response
44        }
45        Err(_) => HttpResponse::InternalServerError().body("Failed to open file"),
46    }
47}