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