𝗦𝗲𝗿𝘃𝗲𝗿 𝗖𝗼𝗻𝗳𝗶𝗴𝘂𝗿𝗮𝘁𝗶𝗼𝗻
Serving static files is a core part of web development. You need to deliver HTML, CSS, JS, and images to your users.
In the Hyperlane framework, you do this using middleware. The middleware intercepts requests and reads files from your disk.
The process involves four steps:
- Path resolution: Map URLs to your file system.
- Content type detection: Find the right MIME type.
- File reading: Pull data from the disk.
- Response delivery: Send the file to the client.
Hyperlane makes this easy with the FileExtension utility. It automatically detects types like: • .html to text/html • .css to text/css • .js to application/javascript • .png to image/png
Best practices for static file serving:
Use asynchronous I/O Always use tokio::fs to read files. This prevents your server from blocking.
Handle directory requests If a path ends in a slash, look for an index.html file. This helps serve websites correctly.
Set correct headers Ensure you send the right Content-Type. If you serve files to other domains, add CORS headers.
Security and errors
- Check file existence to return 404 errors.
- Sanitize paths to prevent directory traversal attacks.
- Use authentication middleware if your assets are private.
Hyperlane gives you the tools to build efficient and secure file servers. You can combine these tools with route filters to control exactly who sees your files.
Project Code: https://github.com/hyperlane-dev/hyperlane
Source: https://dev.to/tengxgfyrz67s/server-configuration-8i7