A very performant and light (2mb in memory) link shortener and tracker. Written in Rust and React and uses Postgres/SQLite.
1use actix_cors::Cors; 2use actix_files as fs; 3use actix_web::{web, App, HttpServer}; 4use anyhow::Result; 5use simplelink::{handlers, AppState}; 6use sqlx::postgres::PgPoolOptions; 7use tracing::info; 8 9#[actix_web::main] 10async fn main() -> Result<()> { 11 // Load environment variables from .env file 12 dotenv::dotenv().ok(); 13 14 // Initialize logging 15 tracing_subscriber::fmt::init(); 16 17 // Database connection string from environment 18 let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set"); 19 20 // Create database connection pool 21 let pool = PgPoolOptions::new() 22 .max_connections(5) 23 .acquire_timeout(std::time::Duration::from_secs(3)) 24 .connect(&database_url) 25 .await?; 26 27 // Run database migrations 28 sqlx::migrate!("./migrations").run(&pool).await?; 29 30 let state = AppState { db: pool }; 31 32 let host = std::env::var("SERVER_HOST").unwrap_or_else(|_| "127.0.0.1".to_string()); 33 let port = std::env::var("SERVER_PORT").unwrap_or_else(|_| "8080".to_string()); 34 info!("Starting server at http://{}:{}", host, port); 35 36 // Start HTTP server 37 HttpServer::new(move || { 38 let cors = Cors::default() 39 .allow_any_origin() 40 .allow_any_method() 41 .allow_any_header() 42 .max_age(3600); 43 44 App::new() 45 .wrap(cors) 46 .app_data(web::Data::new(state.clone())) 47 .service( 48 web::scope("/api") 49 .route("/shorten", web::post().to(handlers::create_short_url)) 50 .route("/links", web::get().to(handlers::get_all_links)) 51 .route("/links/{id}", web::delete().to(handlers::delete_link)) 52 .route( 53 "/links/{id}/clicks", 54 web::get().to(handlers::get_link_clicks), 55 ) 56 .route( 57 "/links/{id}/sources", 58 web::get().to(handlers::get_link_sources), 59 ) 60 .route("/auth/register", web::post().to(handlers::register)) 61 .route("/auth/login", web::post().to(handlers::login)) 62 .route("/health", web::get().to(handlers::health_check)), 63 ) 64 .service(web::resource("/{short_code}").route(web::get().to(handlers::redirect_to_url))) 65 .service(fs::Files::new("/", "./static").index_file("index.html")) 66 }) 67 .workers(2) 68 .backlog(10_000) 69 .bind(format!("{}:{}", host, port))? 70 .run() 71 .await?; 72 73 Ok(()) 74}