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 Link Generation
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
impl Redirector
Sourcepub fn new<S: ToString>(long_path: S) -> Result<Self, RedirectorError>
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 filesErr(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
Sourcepub fn short_file_name(&self) -> OsString
pub fn short_file_name(&self) -> OsString
Sourcepub fn set_path<P: Into<PathBuf>>(&mut self, path: P)
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
Sourcepub fn write_redirect(&self) -> Result<String, RedirectorError>
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 successfulErr(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
impl Clone for Redirector
Source§fn clone(&self) -> Redirector
fn clone(&self) -> Redirector
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moreSource§impl Debug for Redirector
impl Debug for Redirector
Source§impl Default for Redirector
impl Default for Redirector
Source§fn default() -> Redirector
fn default() -> Redirector
Source§impl Display for Redirector
impl Display for Redirector
Source§fn fmt(&self, f: &mut Formatter<'_>) -> Result
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.