Basic redirection working

This commit is contained in:
SinTan1729
2023-04-02 22:26:23 -05:00
parent 0e97516759
commit b9d76b6734
7 changed files with 139 additions and 27 deletions

23
actix/src/database.rs Normal file
View File

@@ -0,0 +1,23 @@
use sqlite::{open, Row};
pub fn find_url(shortlink: &str) -> String {
let db = open("./urls.sqlite").expect("Unable to open database!");
let query = "SELECT long_url FROM urls WHERE short_url = ?";
let statement: Vec<Row> = db
.prepare(query)
.unwrap()
.into_iter()
.bind((1, shortlink))
.unwrap()
.map(|row| row.unwrap())
.collect();
let mut longlink = "";
if statement.len() == 1 {
longlink = statement[0].read::<&str, _>("long_url");
}
String::from(longlink)
}

View File

@@ -1,19 +1,44 @@
use actix_files::Files;
use actix_web::{get, web, App, HttpServer, Responder};
use actix_files::{Files, NamedFile};
use actix_web::{
get,
web::{self, Redirect},
App, HttpServer, Responder,
};
mod database;
mod utils;
#[get("/hello/{name}")]
async fn greet(name: web::Path<String>) -> impl Responder {
format!("Hello {name}!")
// Define the routes
// Add new links
// Return all active links
// 404 error page
#[get("/err/404")]
async fn error404() -> impl Responder {
NamedFile::open_async("./resources/404.html").await
}
#[actix_web::main] // or #[tokio::main]
// 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()
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(greet)
.service(link_handler)
.service(error404)
.service(Files::new("/", "./resources/").index_file("index.html"))
})
.bind(("127.0.0.1", 2000))?
.bind(("0.0.0.0", 2000))?
.run()
.await
}

16
actix/src/utils.rs Normal file
View File

@@ -0,0 +1,16 @@
use crate::database;
use actix_web::web;
use regex::Regex;
pub fn get_longurl(shortlink: web::Path<String>) -> String {
if validate_link(&shortlink) {
database::find_url(shortlink.as_str())
} else {
String::from("")
}
}
fn validate_link(link: &str) -> bool {
let re = Regex::new("[a-z0-9-_]+").unwrap();
re.is_match(link)
}