### Mock JSON Rule Example in LightProxy Source: https://github.com/alibaba/lightproxy/blob/master/docs/docs/doc/getting-started.md Demonstrates how to create a JSON mock rule in LightProxy. This rule uses an ES6-like multi-line string syntax, an extension of whistle's grammar, allowing for direct multi-line content within the rule definition. This enables quick mocking of interfaces with custom JSON responses and headers. ```whistle ``` // Mock JSON 'https://www.github.com/alibaba/lightproxy' http://127.0.0.1:8888/mock/data.json ``` ``` // Mock JSON with custom header 'https://www.github.com/alibaba/lightproxy' http://127.0.0.1:8888/mock/data.json { response://header.name my-test-head } ``` ``` -------------------------------- ### Install whistle.chii Plugin Source: https://github.com/alibaba/lightproxy/blob/master/vendor/whistle.chii-internal/README.md Installs the whistle.chii plugin globally using npm. This command requires Node.js and npm to be installed on your system. ```bash npm install whistle.chii -g ``` -------------------------------- ### Example Curl Request Through LightProxy (Shell) Source: https://github.com/alibaba/lightproxy/blob/master/docs/docs/doc/cli.md This example demonstrates how to use `curl` to make a request after setting the proxy environment variables. The output shows the `Proxy-Agent` header indicating that the request went through LightProxy, followed by the actual HTTP response. ```shell curl https://baidu.com -I ``` -------------------------------- ### Umi/Antd Pro Development Integration for HMR and Assets Source: https://context7.com/alibaba/lightproxy/llms.txt Configure LightProxy to facilitate local development for Umi or Antd Pro projects. This setup handles Hot Module Replacement (HMR), asynchronous chunks, and CDN resource loading by forwarding requests to the local development server. ```bash # Forward main JS/CSS files to local dev server g.alicdn.com/ife/project/umi.css http://127.0.0.1:8000/umi.css g.alicdn.com/ife/project/umi.js http://127.0.0.1:8000/umi.js # Forward async chunks and source maps ^www.test.com/***.js http://127.0.0.1:8000/$1.js ^www.test.com/***.map http://127.0.0.1:8000/$1.map ^www.test.com/***.css http://127.0.0.1:8000/$1.css # Forward HMR websocket connections ^www.test.com/sockjs-node/*** http://127.0.0.1:8000/sockjs-node/$1 # Forward umi-ui requests www.test.com:3000 http://127.0.0.1:3000/ # Optional: Forward API requests to local backend ^www.test.com/api/*** http://127.0.0.1:8000/api/$1 ``` -------------------------------- ### Example Usage of BRLOptionParser in Objective-C Source: https://github.com/alibaba/lightproxy/blob/master/vendor/proxy_conf_helper/BRLOptionParser/README.markdown This Objective-C code demonstrates how to use BRLOptionParser to parse command-line arguments. It shows how to set a banner, add options with descriptions and arguments, handle errors, and execute custom blocks for options like '--help'. ```objective-c // main.m #import int main(int argc, const char * argv[]) { @autoreleasepool { NSString *name = @"world"; BOOL verbose = NO; BRLOptionParser *options = [BRLOptionParser new]; [options setBanner:@"usage: %s [-n ] [-vh]", argv[0]]; [options addOption:"name" flag:'n' description:@"Your name" argument:&name]; [options addSeparator]; [options addOption:"verbose" flag:'v' description:nil value:&verbose]; __weak typeof(options) weakOptions = options; [options addOption:"help" flag:'h' description:@"Show this message" block:^{ printf("%s", [[weakOptions description] UTF8String]); exit(EXIT_SUCCESS); }]; NSError *error = nil; if (![options parseArgc:argc argv:argv error:&error]) { const char * message = error.localizedDescription.UTF8String; fprintf(stderr, "%s: %s\n", argv[0], message); exit(EXIT_FAILURE); } if (verbose) { fprintf(stderr, "(Preparing to say hello...)\n"); } printf("Hello, %s!\n", name.UTF8String); } return EXIT_SUCCESS; } ``` -------------------------------- ### Wildcard Matching Rules (Lightproxy Syntax) Source: https://github.com/alibaba/lightproxy/blob/master/docs/docs/rules/match.md Defines rules for wildcard matching in Lightproxy, using '^' to start, '*' and '***' as wildcards, and '$' for capture groups. '*' matches up to '/', while '***' matches multiple path segments. '$0' represents the entire URL. ```lightproxy # Wildcard matching must start with ^ # Visit g.alicdn.com/abc/xyz/1.js and it will be mapped to /path/to/xyz/1.js ^ g.alicdn.com / abc / *** / path / to / $ 1 # You can also use $ to limit the end # Only forward URLs ending in index.js ^ g.alicdn.com / abc / *** index.js $ / path / to / $ 1 ``` -------------------------------- ### Whistle Rule Syntax: OperatorURI Examples Source: https://github.com/alibaba/lightproxy/blob/master/vendor/whistle/README.md Illustrates the operatorURI part of a whistle rule, which specifies the operation to perform on a matched request. It covers `host` for setting the server IP and `file` for replacing requests with local files. Examples show how to specify the opValue for each operation. ```whistle # host:setting requested server IP pattern host://opValue # file:using the local file to replace pattern file://opValue # host:setting requested server IP pattern host://127.0.0.1:6666 # or pattern 127.0.0.1:6666 # file:using the local file to replace pattern file:///User/test/dirOrFile # or pattern /User/test/dirOrFile pattern file://E:\\test\\dirOrFile # or pattern E:\\test\\dirOrFile ``` -------------------------------- ### Whistle Rule Syntax: Pattern Matching Examples Source: https://github.com/alibaba/lightproxy/blob/master/vendor/whistle/README.md Demonstrates various ways to define patterns for matching target request URLs in whistle. This includes matching domains, domains with ports, protocols, paths, regular expressions, and wildcard characters. These patterns are crucial for configuring whistle's request manipulation rules. ```whistle # matching domain www.example.com # domain with port www.example.com:6666 # domain with protocol, supporting http, https, ws, wss, tunnel http://www.example.com # matching path, supporting protocol, port www.example.com/test https:/www.exapmle.com/test https:/www.exapmle.com:6666/test # matching regular expression /^https?://www\.example\.com\/test\/(.*)/ referer://http://www.test.com/$1 # matching wildcard ^www.example.com/test/*** referer://http://www.test.com/$1 ``` -------------------------------- ### Install BRLOptionParser with CocoaPods Source: https://github.com/alibaba/lightproxy/blob/master/vendor/proxy_conf_helper/BRLOptionParser/README.markdown This snippet shows how to add the BRLOptionParser library to your project using CocoaPods. It specifies the dependency in the Podfile. ```ruby # Podfile pod 'BRLOptionParser', '~> 0.3.1' ``` -------------------------------- ### Node.js Inline Rule Script for LightProxy Source: https://github.com/alibaba/lightproxy/blob/master/docs/docs/doc/write-rule-in-nodejs.md An example of an inline Node.js script for LightProxy rules. It demonstrates how to access request details (URL, headers, method, body) and modify the response. The `next()` function is used to forward the request, and the response can be intercepted and modified before being sent back. ```javascript github.com/alibaba/lightproxy scriptfile://` exports.handleRequest = async (ctx, next) => { // do sth // ctx.fullUrl request url // ctx.headers request header // ctx.options some meta infomation // ctx.method request method // const reqBody = await ctx.getReqBody(); req body buffer // const reqText = await ctx.getReqText(); req body text, or '' // const formData = await ctx.getReqForm(); req form data, or {} // ctx.req.body = String| Buffer | Stream | null // next can use with next({ host, port }); // use next to send request const { statusCode, headers } = await next(); // do sth // const resBody = yield ctx.getResBody(); // const resText = yield ctx.getResText(); // ctx.status = 404; // ctx.set(headers); // ctx.set('x-test', 'abc'); // ctx.body = String| Buffer | Stream | null; ctx.body = 'test'; }; ` ``` -------------------------------- ### Proxy Configuration for Umi/Antd-Pro Static Assets Source: https://github.com/alibaba/lightproxy/blob/master/docs/docs/doc/use-with-umi-antd-pro.md This configuration forwards static assets (JS, CSS, map files) from a CDN to a local development server. It also handles proxying for HMR (Hot Module Replacement) and other dynamic features provided by Umi during local development. Adjust domain names and ports as per your project setup. ```nginx # Proxy two main files, modify according to specific URL g.alicdn.com/ife/project/umi.css http://127.0.0.1:8000/umi.css g.alicdn.com/ife/project/umi.js http://127.0.0.1:8000/umi.js # Locally developed asynchronously loaded async js/css and vendor will be loaded from/, so do the corresponding forwarding ^www.test.com/***. js http://127.0.0.1:8000/$1.js ^www.test.com/***. map http://127.0.0.1:8000/$1.map ^www.test.com/***. css http://127.0.0.1:8000/$1.css # /socksjs-node/is used by the HMR function, the following ws/xhr should be forwarded ^www.test.com/sockjs-node/*** http://127.0.0.1:8000/sockjs-node/$1 #: 3000/is the interface used by umi-ui, also forwarded in the past www.test.com:3000 http://127.0.0.1:3000/ # Generally, this is not needed, because the online API is often directly on the online API, but if necessary, you can add # Forward API to local # ^www.test.com/api/*** http://127.0.0.1:8000/api/$1 ``` -------------------------------- ### Configure Chii Rule for Whistle Source: https://github.com/alibaba/lightproxy/blob/master/vendor/whistle.chii-internal/README.md Example of how to configure a rule in Whistle to use the chii plugin for a specific domain. This rule directs traffic for 'chii.liriliri.io' to be processed by the 'whistle.chii' plugin, likely for inspection purposes. ```whistle chii.liriliri.io whistle.chii://title ``` -------------------------------- ### Path Matching (Lightproxy Syntax) Source: https://github.com/alibaba/lightproxy/blob/master/docs/docs/rules/match.md Demonstrates matching all requests under a specific path in Lightproxy. The rule can also be limited by protocol. ```lightproxy test.com/test/ (test) # The agreement can also be limited http://test.com/test/ (test) ``` -------------------------------- ### Domain Wildcard Matching (Lightproxy Syntax) Source: https://github.com/alibaba/lightproxy/blob/master/docs/docs/rules/match.md Illustrates domain wildcard matching in Lightproxy. A single '*' matches a subdomain part (e.g., '*.com'), while '***' matches multiple subdomain levels (e.g., '***.com'). ```lightproxy * .com (test) ***. com (test) ``` -------------------------------- ### Direct Domain Matching (Lightproxy Syntax) Source: https://github.com/alibaba/lightproxy/blob/master/docs/docs/rules/match.md Shows how to directly match specific domain names in Lightproxy. Rules can optionally include the protocol (http/https) and port number. ```lightproxy test.com (test) # Can limit the agreement http://test.com (test) # Port number can be limited http://test.com:8000 (test) ``` -------------------------------- ### Regular Expression Matching (Lightproxy Syntax) Source: https://github.com/alibaba/lightproxy/blob/master/docs/docs/rules/match.md Explains how to use regular expressions for flexible matching in Lightproxy, enclosed in '/'. It supports capture groups '$1' through '$9' and '$0' for the entire URL. ```lightproxy # Match all requests /./ (test) # Match the request that contains a keyword in the url / keyword / (test) # Through regular matching, the same $ 1 ~ $ 9 capture group, $ 0 means the entire URL /(\d+).html/ (test) ``` -------------------------------- ### Node.js External Rule File for LightProxy Source: https://github.com/alibaba/lightproxy/blob/master/docs/docs/doc/write-rule-in-nodejs.md This demonstrates how to configure LightProxy to use an external JavaScript file for custom rules. The rule is specified by providing the path to the `.js` file after `scriptfile://` in the configuration. ```javascript github.com/alibaba/lightproxy scriptfile:/path/to/file.js ``` -------------------------------- ### Simulating Network Conditions with Response Delay and Speed Throttling Source: https://context7.com/alibaba/lightproxy/llms.txt Simulate slow network conditions by introducing delays to requests or responses, and by limiting bandwidth. This is essential for testing how applications behave under various network constraints, including loading states and timeout handling. ```bash # Add delay to request (milliseconds) api.example.com reqDelay://2000 # Add delay to response (milliseconds) api.example.com resDelay://3000 # Limit request upload speed (KB/s) api.example.com reqSpeed://50 # Limit response download speed (KB/s) api.example.com resSpeed://100 # Combine delay and speed limiting api.example.com resDelay://1000 resSpeed://50 ``` -------------------------------- ### Set Command Line Proxy Environment Variables (Shell) Source: https://github.com/alibaba/lightproxy/blob/master/docs/docs/doc/cli.md This script sets the `https_proxy`, `http_proxy`, and `all_proxy` environment variables to direct traffic through the LightProxy instance. It is intended to be executed in a shell environment. Applications that read these environment variables will then use the specified proxy. ```shell export https_proxy=http://127.0.0.1:12888 http_proxy=http://127.0.0.1:12888 all_proxy=socks5://127.0.0.1:12889 ``` -------------------------------- ### Proxy Chaining with SOCKS and HTTP Proxies Source: https://context7.com/alibaba/lightproxy/llms.txt Configure LightProxy to forward requests through other proxy servers like SOCKS5 or HTTP. This is useful for scenarios involving VPNs or corporate networks that require traffic to be routed through specific exit points. ```bash # Forward specific URLs through SOCKS proxy /internal\.corp\.com/ socks://127.0.0.1:1080 # Forward all traffic through SOCKS proxy /.*/ socks://127.0.0.1:1080 # Forward through HTTP proxy /api\.external\.com/ proxy://127.0.0.1:8888 # Forward through HTTPS proxy /secure\.example\.com/ https-proxy://127.0.0.1:8443 ``` -------------------------------- ### Custom Window Opening in JavaScript Source: https://github.com/alibaba/lightproxy/blob/master/vendor/whistle/biz/webui/htdocs/index.html This JavaScript code intercepts calls to `window.open`. If the URL is 'editor.html' or 'preview.html', it creates a modal-like div to display the content in an iframe. Otherwise, it uses the Electron remote shell to open the URL externally. This allows for in-app previews or editing while maintaining external links. ```javascript const require = parent && parent.window && parent.window.require; let lastCleanup; if (require) { const originOpen = window.open; window.open = (url) => { console.log('url', url); if (url === 'editor.html' || url === 'preview.html') { if (lastCleanup) { lastCleanup(); lastCleanup = null; } const floatLayer = document.createElement('div'); floatLayer.style = ` position: fixed; width: 90%; height: 80%; left: 5%; top: 10%; z-index: 1000; display: flex; flex-direction: column; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, .1), 0 10px 10px -5px rgba(0, 0, 0, .04); border: 1px solid #c0c0c0; border-radius: 6px; overflow: hidden; background-color: #fff; `.replace('\n', ''); const layerBar = document.createElement('div'); layerBar.style = ` width: 100%; height: 0; flex: 0 0 28px; background-color: #f5f5f5; display: flex; align-items: center; padding: 0 10px; `.replace('\n', ''); const container = document.createElement('iframe'); container.src = url; container.style = ` width: 100%; flex: 1; border: 0; `.replace('\n', ''); floatLayer.appendChild(layerBar); floatLayer.appendChild(container); document.body.appendChild(floatLayer); const closeBtn = document.createElement('div'); closeBtn.style = ` cursor: pointer; height: 13px; width: 13px; border-radius: 50%; border: 1px solid #e2463f; background-color: #ff5f57 !important; `.replace('\n', ''); const cleanup = () => { closeBtn.remove(); layerBar.remove(); container.remove(); floatLayer.remove(); }; closeBtn.onclick = cleanup; lastCleanup = cleanup; layerBar.appendChild(closeBtn); return { set setValue(val) { container.contentWindow.setValue = val; }, set getValue(val) { container.contentWindow.getValue = val; } } } else { require('electron').remote.shell.openExternal(url); } }; } ``` -------------------------------- ### Configure Hosts with IP Addresses Source: https://github.com/alibaba/lightproxy/blob/master/vendor/whistle/README.md Configure hostnames to resolve to specific IP addresses or ports. This is useful for local development and testing by directing traffic to local servers or specific network interfaces. Supports both IPv4 and IPv6. ```plaintext www.ifeng.com 127.0.0.1 # or 127.0.0.1 www.ifeng.com # www.ifeng.com 127.0.0.1 www.ifeng.com 127.0.0.1:8080 # or 127.0.0.1:8080 www.ifeng.com ``` -------------------------------- ### Configure Hosts with Domain Forwarding Source: https://github.com/alibaba/lightproxy/blob/master/vendor/whistle/README.md Forward requests from one domain to another, optionally specifying a port. This allows testing how a site behaves when served from a different domain or port, useful for proxying and load balancing configurations. ```plaintext www.ifeng.com host://www.qq.com:8080 # or host://www.qq.com:8080 www.ifeng.com ``` -------------------------------- ### Initialize Whistle Bridge and Event Listeners (JavaScript) Source: https://github.com/alibaba/lightproxy/blob/master/vendor/whistle/assets/menu.html Initializes the `whistleBridge` object, which provides an interface for interacting with the Lightproxy environment. It sets up methods for managing listeners for network, rules, and values, and handles event emission. It also includes a mechanism for delayed initialization and event processing. ```javascript (function() { var config = window.whistleMenuConfig; var list = []; var networkListeners = []; var rulesListeners = []; var valuesListeners = []; var handleOnLoad = function() { timer = null; list.forEach(emit); list = null; }; var timer = setTimeout(handleOnLoad, 12000); function execListeners(listeners, options) { listeners.forEach(function(fn) { try { fn(options) } catch (e) { console.error(e); } }); } function emit(options) { switch(options.type) { case 'rules': execListeners(rulesListeners, options); break; case 'values': execListeners(valuesListeners, options); break; default: execListeners(networkListeners, options); } } window.onWhistleContextMenuClick = function(options) { if (list) { list.push(options); } else { emit(options); } }; var delayOnLoad = function() { if (timer) { setTimeout(handleOnLoad, 100); clearTimeout(timer); timer = null; } }; window.onload = delayOnLoad; try { window.addEventListener('load', delayOnLoad); } catch (e) {} var toast = {}; var modal = {}; window.whistleBridge = { config: config, modal: modal, toast: toast, addNetworkListener: function(l) { if (typeof l === 'function' && networkListeners.indexOf(l) === -1) { networkListeners.push(l); } }, removeNetworkListener: function(l) { l = networkListeners.indexOf(l); if (l !== -1) { networkListeners.splice(l, 1); } }, removeAllNetworkListeners: function() { networkListeners = []; }, addRulesListener: function(l) { if (typeof l === 'function' && rulesListeners.indexOf(l) === -1) { rulesListeners.push(l); } }, removeRulesListener: function(l) { l = rulesListeners.indexOf(l); if (l !== -1) { rulesListeners.splice(l, 1); } }, removeAllRulesListeners: function() { rulesListeners = []; }, addValuesListener: function(l) { if (typeof l === 'function' && valuesListeners.indexOf(l) === -1) { valuesListeners.push(l); } }, removeValuesListener: function(l) { l = valuesListeners.indexOf(l); if (l !== -1) { valuesListeners.splice(l, 1); } }, removeAllValuesListeners: function() { valuesListeners = []; } }; try { window.initWhistleBridge = function(options) { window.initWhistleBridge = function() {}; Object.keys(options.msgBox).forEach(function(name) { toast[name] = options.msgBox[name]; }); window.whistleBridge.importSessions = options.importSessions; window.whistleBridge.request = options.request; window.whistleBridge.createRequest = options.createRequest; window.whistleBridge.showModal = options.showModal; window.whistleBridge.createModal = options.createModal; window.whistleBridge.importRules = options.importRules; window.whistleBridge.importValues = options.importValues; }; window.parent.onPluginContextMenuReady(window); } catch (e) {} })(); ``` -------------------------------- ### Configuring Cross-Origin Resource Sharing (CORS) Source: https://context7.com/alibaba/lightproxy/llms.txt Enable and configure Cross-Origin Resource Sharing (CORS) headers for API development and testing. This allows web applications from different origins to access resources hosted on your server, essential for modern web development. ```bash # Enable CORS for requests api.example.com reqCors://* # Enable CORS for responses with all origins api.example.com resCors://* # Configure specific CORS headers api.example.com resCors://{cors-config} # cors-config in Values: # access-control-allow-origin: https://app.example.com # access-control-allow-methods: GET, POST, PUT, DELETE # access-control-allow-headers: Content-Type, Authorization ``` -------------------------------- ### Custom Request/Response Handling with Node.js Scripts Source: https://context7.com/alibaba/lightproxy/llms.txt Implement custom logic for handling requests and responses using Node.js scripts. These scripts can access and modify request context, headers, body, and programmatically alter responses before they are sent. ```bash # Inline Node.js script rule github.com/alibaba/lightproxy scriptfile://` exports.handleRequest = async (ctx, next) => { // Access request properties // ctx.fullUrl - full request URL // ctx.headers - request headers // ctx.method - HTTP method // ctx.options - meta information // Get request body const reqBody = await ctx.getReqBody(); // Buffer const reqText = await ctx.getReqText(); // String const formData = await ctx.getReqForm(); // Form data object // Modify request body before sending ctx.req.body = JSON.stringify({ modified: true }); // Forward request and get response const { statusCode, headers } = await next(); // Get response body const resBody = await ctx.getResBody(); const resText = await ctx.getResText(); // Modify response ctx.status = 200; ctx.set('x-custom-header', 'modified'); ctx.body = JSON.stringify({ original: JSON.parse(resText), timestamp: Date.now() }); }; ` # Or reference external script file api.example.com scriptfile:///Users/dev/scripts/handler.js ``` -------------------------------- ### Replace Responses with Local Files Source: https://github.com/alibaba/lightproxy/blob/master/vendor/whistle/README.md Replace remote server responses with content from local files. This is highly beneficial for front-end development, allowing developers to work on UI elements and assets locally without redeploying to a server. Supports different path separators for Mac/Linux and Windows. ```plaintext # Mac or Linux www.ifeng.com file:///User/username/test # or www.ifeng.com file:///User/username/test/index.html # Both '\' and '/' can be used as path separator for Widows www.ifeng.com file://E:\xx\test # or www.ifeng.com file://E:\xx\test\index.html ``` -------------------------------- ### Inject HTML, JS, and CSS Content Source: https://github.com/alibaba/lightproxy/blob/master/vendor/whistle/README.md Inject custom HTML, JavaScript, or CSS into web page responses. Lightproxy intelligently determines how to inject the content based on the response type, wrapping JS in `