chhoto-url/actix/src/main.rs

62 lines
1.4 KiB
Rust
Raw Normal View History

2023-04-04 04:50:23 +10:00
use std::env;
2023-04-03 13:26:23 +10:00
use actix_files::{Files, NamedFile};
use actix_web::{
get,
web::{self, Redirect},
2023-04-04 02:55:27 +10:00
App, HttpResponse, HttpServer, Responder,
2023-04-03 13:26:23 +10:00
};
mod database;
mod utils;
2023-04-03 07:53:55 +10:00
2023-04-03 13:26:23 +10:00
// Define the routes
// Add new links
// Return all active links
2023-04-04 02:55:27 +10:00
#[get("/api/all")]
async fn getall() -> HttpResponse {
HttpResponse::Ok().body(utils::getall())
}
2023-04-04 04:50:23 +10:00
// Get the site URL
#[get("/api/siteurl")]
async fn siteurl() -> HttpResponse {
let site_url = env::var("site_url").unwrap_or(String::from("unset"));
println!("{site_url}");
HttpResponse::Ok().body(site_url)
}
2023-04-03 13:26:23 +10:00
// 404 error page
#[get("/err/404")]
async fn error404() -> impl Responder {
NamedFile::open_async("./resources/404.html").await
}
// Handle a given shortlink
#[get("/{shortlink}")]
async fn link_handler(shortlink: web::Path<String>) -> impl Responder {
let longlink = utils::get_longurl(shortlink);
if longlink == String::from("") {
Redirect::to("/err/404")
} else {
Redirect::to(longlink).permanent()
}
2023-04-03 07:53:55 +10:00
}
2023-04-03 13:26:23 +10:00
#[actix_web::main]
2023-04-03 07:53:55 +10:00
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
2023-04-03 13:26:23 +10:00
.service(link_handler)
.service(error404)
2023-04-04 02:55:27 +10:00
.service(getall)
2023-04-04 04:50:23 +10:00
.service(siteurl)
2023-04-03 07:53:55 +10:00
.service(Files::new("/", "./resources/").index_file("index.html"))
})
2023-04-03 13:26:23 +10:00
.bind(("0.0.0.0", 2000))?
2023-04-03 07:53:55 +10:00
.run()
.await
}