Ability to add new links

This commit is contained in:
SinTan1729
2023-04-03 17:40:37 -05:00
parent 618fd0e53a
commit 7f6ba5175f
5 changed files with 93 additions and 7 deletions

View File

@@ -2,7 +2,7 @@ use std::env;
use actix_files::{Files, NamedFile};
use actix_web::{
get,
get, post,
web::{self, Redirect},
App, HttpResponse, HttpServer, Responder,
};
@@ -12,9 +12,19 @@ mod utils;
// Define the routes
// Add new links
#[post("/api/new")]
async fn add_link(req: String) -> HttpResponse {
let out = utils::add_link(req);
if out.0 {
println!("ok{}", out.1);
HttpResponse::Ok().body(out.1)
} else {
println!("bad{}", out.1);
HttpResponse::BadRequest().body(out.1)
}
}
// Return all active links
#[get("/api/all")]
async fn getall() -> HttpResponse {
HttpResponse::Ok().body(utils::getall())
@@ -36,8 +46,10 @@ async fn error404() -> impl Responder {
// Handle a given shortlink
#[get("/{shortlink}")]
async fn link_handler(shortlink: web::Path<String>) -> impl Responder {
let longlink = utils::get_longurl(shortlink);
let shortlink_str = shortlink.to_string();
let longlink = utils::get_longurl(shortlink_str);
if longlink == "".to_string() {
database::add_hit(shortlink.as_str());
Redirect::to("/err/404")
} else {
Redirect::to(longlink).permanent()
@@ -52,6 +64,7 @@ async fn main() -> std::io::Result<()> {
.service(error404)
.service(getall)
.service(siteurl)
.service(add_link)
.service(Files::new("/", "./resources/").index_file("index.html"))
})
.bind(("0.0.0.0", 2000))?