Struct Redirector

Source
pub struct Redirector { /* private fields */ }
Expand description

Manages URL redirection by generating short links and HTML redirect pages.

The Redirector creates HTML files that automatically redirect users to longer URLs on your website. It handles the entire process from URL validation to file generation.

§Key Features

  • URL Validation: Ensures paths contain only valid characters
  • Unique Naming: Generates unique file names using base62 encoding and timestamps
  • HTML Generation: Creates complete HTML pages with meta refresh and JavaScript fallbacks
  • File Management: Handles directory creation and file writing operations

Short file names are generated using:

  • Current timestamp in milliseconds
  • Sum of UTF-16 code units from the URL path
  • Base62 encoding for compact, URL-safe names
  • .html extension for web server compatibility

§HTML Output

Generated HTML files include:

  • Meta refresh tag for immediate redirection
  • JavaScript fallback for better compatibility
  • User-friendly link for manual navigation
  • Proper HTML5 structure and encoding

Implementations§

Source§

impl Redirector

Source

pub fn new<S: ToString>(long_path: S) -> Result<Self, RedirectorError>

Creates a new Redirector instance for the specified URL path.

Validates the provided path and automatically generates a unique short file name. The redirector is initialized with a default output directory of “s”.

§Arguments
  • long_path - The URL path to create a redirect for (e.g., “api/v1/users”)
§Returns
  • Ok(Redirector) - A configured redirector ready to generate redirect files
  • Err(RedirectorError::InvalidUrlPath) - If the path contains invalid characters
§Examples
use link_bridge::Redirector;

// Valid paths
let redirector1 = Redirector::new("api/v1").unwrap();
let redirector2 = Redirector::new("/docs/getting-started/").unwrap();
let redirector3 = Redirector::new("user-profile").unwrap();

// Invalid paths (will return errors)
assert!(Redirector::new("api?param=value").is_err()); // Query parameters
assert!(Redirector::new("api;session=123").is_err());  // Semicolons
assert!(Redirector::new("").is_err());                 // Empty string
Source

pub fn set_path<P: Into<PathBuf>>(&mut self, path: P)

Sets the output directory where redirect HTML files will be stored.

By default, redirector uses “s” as the output directory. Use this method to specify a custom directory path. The directory will be created automatically when write_redirects() is called if it doesn’t exist.

§Arguments
  • path - A path-like value (String, &str, PathBuf, etc.) specifying the directory
§Examples
use link_bridge::Redirector;

let mut redirector = Redirector::new("api/v1").unwrap();

// Set various types of paths
redirector.set_path("redirects");           // &str
redirector.set_path("output/html".to_string()); // String
redirector.set_path(std::path::PathBuf::from("custom/path")); // PathBuf
Source

pub fn write_redirects(&self) -> Result<(), RedirectorError>

Writes the redirect HTML file to the filesystem.

Creates the output directory (if it doesn’t exist) and generates a complete HTML redirect page that automatically redirects users to the target URL. The file name is the automatically generated short name with .html extension.

§File Structure

The generated HTML includes:

  • DOCTYPE and proper HTML5 structure
  • Meta charset and refresh tags for immediate redirection
  • JavaScript fallback for better browser compatibility
  • User-friendly fallback link for manual navigation
§Returns
  • Ok(()) - If the file was successfully created and written
  • Err(RedirectorError::FileCreationError) - If file operations fail
§Errors

Common causes of FileCreationError:

  • Permission denied (insufficient write permissions)
  • Disk full or insufficient space
  • Invalid characters in the file path
  • Parent directory cannot be created
§Examples
use link_bridge::Redirector;
use std::fs;

let mut redirector = Redirector::new("api/v1/users").unwrap();
redirector.set_path("doc_test_redirects");
 
// This creates: doc_test_redirects/{unique_name}.html
redirector.write_redirects().unwrap();
 
// Clean up after the test
fs::remove_dir_all("doc_test_redirects").ok();

Trait Implementations§

Source§

impl Clone for Redirector

Source§

fn clone(&self) -> Redirector

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Redirector

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Redirector

Source§

fn default() -> Redirector

Returns the “default value” for a type. Read more
Source§

impl Display for Redirector

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Generates the complete HTML redirect page content.

Creates a standard HTML5 page that redirects to the target URL using multiple methods for maximum compatibility:

  • Meta refresh tag (works in all browsers)
  • JavaScript redirect (faster, works when JS is enabled)
  • Fallback link (for manual navigation if automatic redirect fails)

The HTML follows web standards and includes proper accessibility features.

Source§

impl PartialEq for Redirector

Source§

fn eq(&self, other: &Redirector) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for Redirector

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.