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_web::{web, App, HttpServer};
3use anyhow::Result;
4use simple_link::{handlers, AppState};
5use sqlx::postgres::PgPoolOptions;
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 let host = std::env::var("SERVER_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
32 let port = std::env::var("SERVER_PORT").unwrap_or_else(|_| "8080".to_string());
33 info!("Starting server at http://{}:{}", host, port);
34
35 // Start HTTP server
36 HttpServer::new(move || {
37 let cors = Cors::default()
38 .allow_any_origin()
39 .allow_any_method()
40 .allow_any_header()
41 .max_age(3600);
42
43 App::new()
44 .wrap(cors)
45 .app_data(web::Data::new(state.clone()))
46 .service(
47 web::scope("/api")
48 .route("/shorten", web::post().to(handlers::create_short_url))
49 .route("/links", web::get().to(handlers::get_all_links))
50 .route("/links/{id}", web::delete().to(handlers::delete_link))
51 .route("/auth/register", web::post().to(handlers::register))
52 .route("/auth/login", web::post().to(handlers::login))
53 .route("/health", web::get().to(handlers::health_check)),
54 )
55 .service(web::resource("/{short_code}").route(web::get().to(handlers::redirect_to_url)))
56 })
57 .workers(2)
58 .backlog(10_000)
59 .bind(format!("{}:{}", host, port))?
60 .run()
61 .await?;
62
63 Ok(())
64}