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
  • Registry System: Maintains a JSON registry to track existing redirects and prevent duplicates

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

§Registry System

The redirector maintains a registry.json file in each output directory that tracks:

  • Mapping from URL paths to their corresponding redirect files
  • Prevents duplicate files for the same URL path
  • Ensures consistent redirect behaviour across multiple calls
  • Automatically created and updated when redirects are written

§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 short_file_name(&self) -> OsString

Reports the short file name of the redirect HTML file.

§Returns

An OsString containing the generated file name with .html extension.

§Examples
use link_bridge::Redirector;

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

assert_eq!(redirector.short_file_name(), OsString::from("12aaBB.html"));
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_redirect() 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_redirect(&self) -> Result<String, RedirectorError>

Writes the redirect HTML file to the filesystem with registry support.

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.

§Registry System

This method maintains a registry (registry.json) in the output directory to track existing redirects. If a redirect for the same URL path already exists, it returns the path to the existing file instead of creating a duplicate. This ensures:

  • No duplicate files for the same URL path
  • Consistent redirect behaviour across multiple calls
  • Efficient reuse of existing redirects
§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(String) - The path to the created redirect file if successful
  • Err(RedirectorError::FileCreationError) - If file operations fail
§Errors

This method can return the following errors:

§FileCreationError
  • Permission denied (insufficient write permissions)
  • Disk full or insufficient space
  • Invalid characters in the file path
  • Parent directory cannot be created
§FailedToReadRegistry
  • Corrupted or invalid JSON in registry.json
  • Permission denied when reading/writing registry file
  • Registry file locked by another process
§Examples
§Basic Usage
use link_bridge::Redirector;
use std::fs;

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

// First call creates a new redirect file and registry entry
let redirect_path = redirector.write_redirect().unwrap();
println!("Created redirect at: {}", redirect_path);

// Clean up after the test
fs::remove_dir_all("doc_test_redirects").ok();
§Registry behaviour
use link_bridge::Redirector;
use std::fs;

let mut redirector1 = Redirector::new("api/v1/users").unwrap();
redirector1.set_path("doc_test_registry");

let mut redirector2 = Redirector::new("api/v1/users").unwrap();
redirector2.set_path("doc_test_registry");

// First call creates the file
let path1 = redirector1.write_redirect().unwrap();

// Second call returns the same path (no duplicate file created)
let path2 = redirector2.write_redirect().unwrap();
assert_eq!(path1, path2);

// Clean up
fs::remove_dir_all("doc_test_registry").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.