file
The file protocol is used to map requests to the local file system, returning the content of local files as responses to the client. It is suitable for the following scenarios:
- Setting up a local development environment: Quickly set up a local development server.
- Debugging local front-end pages: Directly debug local HTML, CSS, and JavaScript files.
- API Mocking scenarios: Use local JSON files to simulate API responses.
- Static resource serving: Use a local directory as a static resource server.
Rule Syntax
The file protocol supports multiple ways to specify local file content:
1. Inline Value (Direct Specification)
Write the content to be returned directly in the rule, suitable for short text content. Note: value cannot contain spaces or line breaks.
pattern file://(value) [lineProps...] [filters...]Example:
www.example.com/api/data file://({"status":"ok"})Note: Inline values must be wrapped in parentheses (); otherwise, they will be interpreted as local file paths, which may lead to 404 errors:
# Correct: Returns the string "success"
pattern file://(success)
# Incorrect: Will be treated as a path, potentially causing 404
pattern file://successKey points about the inline value syntax of the file protocol:
- Must use
()to wrap the content.- Content cannot contain spaces or line breaks.
- Can be a string, JSON, HTML fragment, etc.
- Without
(), Whistle will interpret it as a file path or{key}and attempt to load the corresponding file or key value.
2. Embedded Value (Using Code Block)
This method is recommended when dealing with complex content containing spaces, line breaks, or when you want to reuse a configuration.
pattern file://{custom-key.json} [lineProps...] [filters...]
``` custom-key.json
{
"status": "success",
"data": {
"message": "Hello from local file"
}
}
```Best Practice: It is recommended to add a response type suffix (e.g., .json, .html, .css) to the key. Whistle will automatically set the correct Content-Type based on the suffix.
3. Referencing a Value from the Values Panel
When the content is large, you can store it in the Values configuration area.
pattern file://{key-of-values.html} [lineProps...] [filters...]Prerequisite: A key named key-of-values.html with the content to be returned as its value must exist in Values.
Capacity Recommendations:
- Content less than 2KB: Recommended to use inline or embedded methods.
- Content between 2KB and 200KB: Recommended to store in
Values. - Content larger than 200KB: Recommended to use local files.
4. Loading from a Temporary File
Use Whistle's temporary file feature when content needs frequent editing.
pattern file://temp.htmlSteps:
- In the Rules editor, hold down
Command(Mac) /Ctrl(Windows). - Click with the mouse on
file://temp.html. - Enter the response content in the pop-up editing dialog.
- Click
Saveto save.
After saving, the rule will automatically change to a format similar to this:
https://example.com/report file://temp/11adb9c9e1142df67b30d7646ec59bcd34c855d9011d1a2405c7fc2dfc94568d.htmlTo edit again, click the temporary file link in the same way.
5. Loading from a File Path or Remote URL
Load the response content from the local file system or a remote URL.
# Load from a local file
pattern file:///User/xxx/test.html
# Load from a remote URL
pattern file://https://example.com/template.htmlParameter Details
| Parameter | Required | Description & Examples |
|---|---|---|
| pattern | Yes | Expression used to match the request URL. • Supports domains, paths, wildcards, regular expressions. • See Matching Pattern Documentation for details. |
| value | Yes | The file content or path to return, supporting multiple formats: • Local file or directory path • Remote URL • Inline, embedded, Values references |
| lineProps | No | Sets additional properties for the rule. Examples: • lineProps://important: Increase rule priority.• lineProps://weakRule: When both file and proxy rules are configured, the proxy rule will be disabled by default. This property can increase the priority of the proxy rule.• See lineProps Documentation for details. |
| filters | No | Optional filter conditions for precise control over when the rule takes effect. • Can match request URL, method, headers, body content. • Can match response status code, headers. • See Filters Documentation for details. |
Configuration Examples
1. Basic File Path Mapping
# Map a domain to a local directory
www.example.com/path file:///Users/username/projects/my-site
# Windows system path
www.example.com/path file://D:\projects\my-siteFeature Description:
- Automatic path concatenation: Accessing
https://www.example.com/path/x/y/zwill map to/Users/username/projects/my-site/x/y/z. - Disable path concatenation: Use
< >to wrap the path to disable automatic concatenation.txtwww.example.com/path file://</Users/username/projects/my-site/index.html>Accessing
https://www.example.com/path/x/y/zwill only return the file/Users/username/projects/my-site/index.html.
2. JSONP Interface Mocking
# Inline method
www.example.com/jsonp file://`(${query.callback}({"status":"ok"}))`
# Embedded method
``` jsonp-response
${query.callback}({
"status": "error",
"message": "Invalid parameter"
})
```
www.example.com/jsonp file://`{jsonp-response}`Template String Limitations: Template strings cannot take effect directly in the following scenarios:
- When referencing local file paths.
- When referencing remote URLs.
When encountering these limitations, you can use the tpl protocol as an alternative.
3. Using with Filters
# Exclude specific interfaces
www.example.com/api/path file:///Users/username/mock-data excludeFilter://*/api/auth
# Match based on request body content
www.example.com/api/search file:///Users/username/search-results.json includeFilter://b:/"type":\s*"advanced"/i
# Only match POST requests
www.example.com/api/submit file:///Users/username/success.json includeFilter://m:POST4. Multi-directory Search
# Multiple files or directories separated by `|`
www.example.com/static/path file:///path/to/project1|/path/to/project2|/path/to/project3Search Logic:
- Check each directory in order:
/path/to/project1/static/file.js/path/to/project2/static/file.js/path/to/project3/static/file.js
- Return the first existing file found.
- If none are found, return
404 Not Found.
Advanced Usage
Dynamic Path Handling
# Use regex capture groups
/^https?://www\.example\.com/user/(\d+)/profile file:///Users/username/mock/profiles/user-$1.json
# If not limited to numbers, you can use wildcards
^www.example.com/user/*/profile file:///Users/username/mock/profiles/user-$1.jsonEnvironment-Specific Configuration
``` dev-config
{
"apiBase": "http://localhost:3000",
"debugMode": true
}
```
``` prod-config
{
"apiBase": "https://api.example.com",
"debugMode": false
}
```
# Determine if it's a development environment via cookie: env=dev
www.example.com/config file://{dev-config} includeFilter://reqH:cookie=/env=dev/
www.example.com/config file://{prod-config} # Default production environmentCombining with Other Protocols
# First use file to provide static files, then set response headers
www.example.com file:///Users/username/static-files cache://3600
# For non-existent files, use xfile to allow the request to continue
www.example.com xfile:///Users/username/static-filesRelated Protocols
Allow unmatched files to continue access: xfile
- When a local file does not exist, allow the request to continue to the original server.
- Suitable for development scenarios with static resource servers.
Replace with remote URL content: https or http
- Use content from a remote server as the response.
- Note: It is not recommended to use the form
file://https://xxx.
Domain resolution redirection: host
- Modify domain name resolution to direct requests to a specified IP.
Template rendering: tpl
- Supports more complex template rendering and dynamic content generation.
Notes
Path Handling
- Relative paths: Except for rules inside plugins, it is not recommended to use relative paths. Relative paths are relative to the directory where the Whistle configuration file is located.
- Absolute paths: System absolute paths are supported.
- User directory:
~is supported to represent the user's home directory. - Windows paths: Mixing
/and\as path separators is supported.
File Encoding
- Text files: UTF-8 encoding is used by default.
- Encoding issues: If you encounter garbled characters, check the actual encoding format of the file.
Troubleshooting
Q: File Not Found (404)
A: Check:
- Whether the file path is correct.
- Whether the file exists and has read permissions.
- Whether
< >was used to disable path concatenation.
Q: Garbled Characters
A: Check:
- The actual encoding format of the file.
- Whether the
Content-Typeresponse header is correct. - Whether the file content contains illegal characters.
Q: Rule Not Taking Effect
A: Check:
- Whether the rule pattern matches correctly.
- Whether other rules are overriding it.
- Whether the filter conditions are met.
Q: Template Strings Not Taking Effect
A: Check:
- Whether template strings are used in file path or remote URL scenarios.
- If so, use the tpl protocol instead.
Further Reading
- Matching Pattern Documentation: Learn more about URL matching rules.
- Operation Commands Documentation: Learn about multiple ways to load content.
- Additional Configuration: Learn more about special features.
- Filters: Learn more about filter functionalities.