Add main page redirect

This commit is contained in:
Shav Kinderlehrer 2024-04-07 13:35:59 -04:00
parent 407dbdb386
commit 0820a05293
5 changed files with 31 additions and 15 deletions

2
Cargo.lock generated
View File

@ -194,7 +194,7 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]] [[package]]
name = "chela" name = "chela"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"axum", "axum",
"color-eyre", "color-eyre",

View File

@ -1,6 +1,6 @@
[package] [package]
name = "chela" name = "chela"
version = "0.1.0" version = "0.2.0"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -11,7 +11,7 @@ You can create a redirect by navigating to the `/create` page and filling out th
docker run -d \ docker run -d \
-p 3000:3000 \ -p 3000:3000 \
-e DATABASE_URL=postgres://chela:password@dbhost/postgres?sslmode=disable \ -e DATABASE_URL=postgres://chela:password@dbhost/postgres?sslmode=disable \
-e CHELA_HOST=example.com \ -e CHELA_HOST=a.com \
secondsmiles/chela secondsmiles/chela
``` ```
@ -32,7 +32,8 @@ services:
- 3000:3000 - 3000:3000
environment: environment:
- DATABASE_URL=postgres://chela:password@chela-postgres/postgres?sslmode=disable - DATABASE_URL=postgres://chela:password@chela-postgres/postgres?sslmode=disable
- CHELA_HOST=example.com - CHELA_HOST=a.com
- CHELA_MAIN_PAGE_REDIRECT='https://example.com'
depends_on: depends_on:
- chela-postgres - chela-postgres
restart: unless-stopped restart: unless-stopped
@ -52,6 +53,9 @@ The hostname that Chela should refer to itself as. Defaults to `localhost`.
##### `CHELA_LISTEN_ADDRESS` ##### `CHELA_LISTEN_ADDRESS`
The address that Chela should listen on. Defaults to `0.0.0.0`. The address that Chela should listen on. Defaults to `0.0.0.0`.
##### `CHELA_MAIN_PAGE_REDIRECT`
A page that Chela will redirect to when `/` is requested instead of replying with the default homepage.
### Manually ### Manually
#### Build #### Build
```bash ```bash
@ -63,7 +67,7 @@ $ cargo build -r
#### Run #### Run
```bash ```bash
$ export DATABASE_URL=postgres://chela:password@dbhost/postgres?sslmode=disable $ export DATABASE_URL=postgres://chela:password@dbhost/postgres?sslmode=disable
$ export CHELA_HOST=example.com $ export CHELA_HOST=a.com
$ export CHELA_LISTEN_ADDRESS=127.0.0.1 $ export CHELA_LISTEN_ADDRESS=127.0.0.1
$ ./target/release/chela $ ./target/release/chela
``` ```

View File

@ -3,7 +3,7 @@ use std::net::SocketAddr;
use axum::extract::{ConnectInfo, Path}; use axum::extract::{ConnectInfo, Path};
use axum::http::HeaderMap; use axum::http::HeaderMap;
use axum::http::StatusCode; use axum::http::StatusCode;
use axum::response::{Html, IntoResponse}; use axum::response::{Html, IntoResponse, Redirect};
use axum::Extension; use axum::Extension;
use info_utils::prelude::*; use info_utils::prelude::*;
@ -11,7 +11,11 @@ use info_utils::prelude::*;
use crate::ServerState; use crate::ServerState;
use crate::UrlRow; use crate::UrlRow;
pub async fn index(Extension(state): Extension<ServerState>) -> Html<String> { pub async fn index(Extension(state): Extension<ServerState>) -> impl IntoResponse {
if let Some(redirect) = state.main_page_redirect {
return Redirect::temporary(redirect.as_str()).into_response();
}
Html(format!( Html(format!(
r#" r#"
<!DOCTYPE html> <!DOCTYPE html>
@ -27,6 +31,7 @@ pub async fn index(Extension(state): Extension<ServerState>) -> Html<String> {
"#, "#,
state.host, state.host state.host, state.host
)) ))
.into_response()
} }
/// # Panics /// # Panics
@ -47,7 +52,7 @@ pub async fn id(
let item: Result<UrlRow, sqlx::Error> = let item: Result<UrlRow, sqlx::Error> =
sqlx::query_as("SELECT * FROM chela.urls WHERE id = $1") sqlx::query_as("SELECT * FROM chela.urls WHERE id = $1")
.bind(use_id) .bind(use_id.clone())
.fetch_one(&state.db_pool) .fetch_one(&state.db_pool)
.await; .await;
if let Ok(it) = item { if let Ok(it) = item {
@ -74,11 +79,11 @@ pub async fn id(
) )
.into_response(); .into_response();
} }
} else if let Err(err) = item { } else {
warn!("{}", err); warn!("'{}' not found.", use_id);
return ( return (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::NOT_FOUND,
Html(format!("<pre>Internal error: {err}.</pre>")), Html("<pre>Not found.</pre>".to_string()),
) )
.into_response(); .into_response();
} }

View File

@ -1,5 +1,7 @@
use std::net::SocketAddr; use std::net::SocketAddr;
use url::Url;
use axum::routing::{get, post}; use axum::routing::{get, post};
use axum::Router; use axum::Router;
@ -20,6 +22,7 @@ pub struct ServerState {
pub db_pool: Pool<Postgres>, pub db_pool: Pool<Postgres>,
pub host: String, pub host: String,
pub sqids: Sqids, pub sqids: Sqids,
pub main_page_redirect: Option<Url>,
} }
#[derive(Debug, Clone, sqlx::FromRow, PartialEq, Eq)] #[derive(Debug, Clone, sqlx::FromRow, PartialEq, Eq)]
@ -40,9 +43,7 @@ async fn main() -> eyre::Result<()> {
color_eyre::install()?; color_eyre::install()?;
let db_pool = init_db().await?; let db_pool = init_db().await?;
let host = std::env::var("CHELA_HOST").unwrap_or("localhost".to_string()); let host = std::env::var("CHELA_HOST").unwrap_or("localhost".to_string());
let sqids = Sqids::builder() let sqids = Sqids::builder()
.alphabet( .alphabet(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
@ -51,10 +52,12 @@ async fn main() -> eyre::Result<()> {
) )
.blocklist(["create".to_string()].into()) .blocklist(["create".to_string()].into())
.build()?; .build()?;
let main_page_redirect = std::env::var("CHELA_MAIN_PAGE_REDIRECT").unwrap_or_default();
let server_state = ServerState { let server_state = ServerState {
db_pool, db_pool,
host, host,
sqids, sqids,
main_page_redirect: Url::parse(&main_page_redirect).ok(),
}; };
let address = std::env::var("CHELA_LISTEN_ADDRESS").unwrap_or("0.0.0.0".to_string()); let address = std::env::var("CHELA_LISTEN_ADDRESS").unwrap_or("0.0.0.0".to_string());
@ -74,7 +77,11 @@ async fn main() -> eyre::Result<()> {
async fn init_db() -> eyre::Result<Pool<Postgres>> { async fn init_db() -> eyre::Result<Pool<Postgres>> {
let db_pool = PgPoolOptions::new() let db_pool = PgPoolOptions::new()
.max_connections(15) .max_connections(15)
.connect(std::env::var("DATABASE_URL")?.as_str()) .connect(
std::env::var("DATABASE_URL")
.expect("DATABASE_URL must be set")
.as_str(),
)
.await?; .await?;
log!("Successfully connected to database"); log!("Successfully connected to database");