### Terraform Configuration Examples Source: https://edgeone.ai/document/zh/56246 Demonstrates how to use Terraform to configure EdgeOne acceleration and rule engine settings. Includes instructions on installation and initial setup. ```hcl # Terraform configuration for EdgeOne Site Acceleration resource "edgeone_site" "example" { site_name = "my-accelerated-site" # ... other site configurations } resource "edgeone_acceleration_rule" "example" { site_id = edgeone_site.example.id pattern = "*.example.com/*" # ... acceleration rule details } # Terraform configuration for EdgeOne Rule Engine resource "edgeone_rule_engine_rule" "example" { site_id = edgeone_site.example.id name = "block-unwanted-bots" conditions { operator = "Equals" key = "User-Agent" value = "BadBot/1.0" } action { name = "BlockRequest" } } ``` -------------------------------- ### QUIC SDK Integration Guide Source: https://edgeone.ai/document/zh/54208 Guides for downloading and integrating the QUIC SDK for HTTP/3 support. Includes code examples for Android and iOS platforms, along with API documentation. ```text Android SDK Download and Integration Guide API Documentation for Android ``` ```text iOS SDK Download and Integration Guide API Documentation for iOS ``` -------------------------------- ### QUIC SDK Integration Guide Source: https://edgeone.ai/document/zh/overview Provides instructions and code examples for integrating the QUIC SDK. This guide covers downloading, integrating the SDK, and offers code samples for both Android and iOS platforms, along with API documentation. ```Android // Example Android integration code // Please refer to the full documentation for specific details. ``` ```iOS // Example iOS integration code // Please refer to the full documentation for specific details. ``` -------------------------------- ### Edge Functions: QUIC SDK Integration Guide Source: https://edgeone.ai/document/zh/45962 This section provides instructions and code examples for integrating the QUIC SDK, likely for enabling HTTP/3 (QUIC) functionality. It includes platform-specific guides for Android and iOS. ```text SDK 下载和集成指引 Android iOS 代码示例 Android iOS API 文档 Android iOS ``` -------------------------------- ### QUIC SDK Integration Guide Source: https://edgeone.ai/document/zh/56246 Provides guidance on downloading and integrating the QUIC SDK, along with code examples for Android and iOS platforms. It also includes API documentation for both mobile operating systems. ```text SDK Download and Integration Guide Code Examples: * Android * iOS API Documentation: * Android * iOS ``` -------------------------------- ### QUIC SDK Integration Guide Source: https://edgeone.ai/document/zh/54764 Instructions and code examples for integrating the QUIC SDK, enabling HTTP/3 support for improved network performance. Covers Android and iOS platforms. ```text Android SDK 下载和集成指引 API 文档 iOS SDK 概览 API 文档 ``` -------------------------------- ### QUIC SDK Integration Guide (Android) Source: https://edgeone.ai/document/zh/54200 This section provides guidance on downloading and integrating the QUIC SDK for Android. It includes code examples for common use cases and links to detailed API documentation. ```java public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Example: Initialize QUIC SDK QUICManager.initialize(this, "YOUR_API_KEY"); // Example: Make a QUIC request QUICManager.makeRequest("https://example.com", new QUICResponseListener() { @Override public void onSuccess(String response) { Log.d("QUIC_SDK", "Response: " + response); } @Override public void onError(QUICError error) { Log.e("QUIC_SDK", "Error: " + error.getMessage()); } }); } } ``` -------------------------------- ### QUIC SDK Integration Guide Source: https://edgeone.ai/document/zh/55640 Provides instructions and code examples for integrating the QUIC SDK, enabling HTTP/3 support. This includes downloading, integrating the SDK, and sample code for Android and iOS platforms. The SDK facilitates faster and more reliable data transfer over the internet. ```text ## SDK Download and Integration Guide ### Android 1. Download the QUIC SDK for Android from [link]. 2. Integrate the SDK into your Android project by following the instructions in the `README.md` file. ### iOS 1. Download the QUIC SDK for iOS from [link]. 2. Integrate the SDK into your iOS project using CocoaPods or by manually adding the framework. ``` -------------------------------- ### QUIC SDK Integration Guide (iOS) Source: https://edgeone.ai/document/zh/54200 This section provides guidance on downloading and integrating the QUIC SDK for iOS. It includes code examples for common use cases and links to detailed API documentation. ```swift import UIKit import QUICSDK class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Example: Initialize QUIC SDK QUICManager.shared.initialize(apiKey: "YOUR_API_KEY") // Example: Make a QUIC request QUICManager.shared.makeRequest(url: "https://example.com") { response, error in if let error = error { print("QUIC SDK Error: \(error.localizedDescription)") } else if let response = response { print("QUIC SDK Response: \(response)") } } } } ``` -------------------------------- ### QUIC SDK Integration Guide for Android Source: https://edgeone.ai/document/zh/54506 Provides instructions and code examples for integrating the QUIC SDK into an Android application. This allows for the use of HTTP/3 (QUIC) protocol for faster and more reliable data transfer. It covers SDK download, integration steps, and basic usage. ```java String sdkPath = "path/to/downloaded/sdk"; // Add the following line to your app's build.gradle file: // implementation files("path/to/downloaded/sdk/quic.jar") // Example usage in your application: QuicManager quicManager = new QuicManager(this); quicManager.initialize(); // ... use quicManager for network requests ``` -------------------------------- ### Terraform Configuration Examples Source: https://edgeone.ai/document/zh/54208 Examples of using Terraform to configure EdgeOne AI services, including site acceleration and rule engine settings. ```hcl resource "edgeone_site" "example" { name = "example.com" origin { host = "origin.example.com" } } resource "edgeone_acceleration" "example" { site_id = edgeone_site.example.id // ... other acceleration configurations } ``` ```hcl resource "edgeone_rule_engine" "example" { site_id = edgeone_site.example.id rules { action = "redirect" condition { match = "eq" field = "uri" value = "/old-page.html" } redirect { target = "/new-page.html" status_code = 301 } } } ``` -------------------------------- ### Edge Function Examples for EdgeOne Source: https://edgeone.ai/document/zh/45963 A collection of example Edge Functions demonstrating various use cases, such as returning HTML pages, JSON data, fetching remote resources, authentication, modifying headers, A/B testing, setting cookies, and more. These examples showcase the flexibility and power of EdgeOne's serverless compute capabilities. ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { return new Response("Hello EdgeOne!", { headers: {"content-type": "text/plain"} }) } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const response = { message: "Hello from EdgeOne AI!", timestamp: Date.now() } return new Response(JSON.stringify(response), { headers: {"content-type": "application/json"} }) } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const url = new URL(request.url); const originalUrl = "https://example.com" + url.pathname; try { const remoteResponse = await fetch(originalUrl); return new Response(remoteResponse.body, { status: remoteResponse.status, headers: remoteResponse.headers }); } catch (error) { return new Response("Error fetching remote resource", { status: 500 }); } } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const authHeader = request.headers.get("Authorization"); if (!authHeader || authHeader !== "Bearer YOUR_SECRET_TOKEN") { return new Response("Unauthorized", { status: 401 }); } return fetch(request); } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const response = await fetch(request); const newHeaders = new Headers(response.headers); newHeaders.set("X-EdgeOne-Processed", "true"); return new Response(response.body, { status: response.status, headers: newHeaders }); } ``` ```javascript addEventListener("fetch", event => { const url = new URL(event.request.url); const variant = url.searchParams.get("variant"); if (variant === "B") { event.respondWith(fetch("https://variant-b.example.com")); } else { event.respondWith(fetch("https://variant-a.example.com")); } }) ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const response = await fetch(request); const newHeaders = new Headers(response.headers); newHeaders.append("Set-Cookie", "edgeone_cookie=example; Max-Age=3600; Path=/"); return new Response(response.body, { status: response.status, headers: newHeaders }); } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const region = request.headers.get("CF-IPCountry"); // Example header for country if (region === "JP") { return Response.redirect("https://example.jp/", 302); } else { return fetch(request); } } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const url = new URL(request.url); const cacheKey = url.pathname; const cache = caches.default; let response = await cache.match(request); if (!response) { response = await fetch(request); if (response.ok) { await cache.put(request, response.clone()); } } return response; } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const url = new URL(request.url); // Only cache POST requests if they are for a specific path if (request.method === "POST" && url.pathname === "/api/cacheable") { const cache = caches.default; let response = await cache.match(request); if (!response) { response = await fetch(request); if (response.ok) { await cache.put(request, response.clone()); } } return response; } return fetch(request); } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const stream = new ReadableStream({ start(controller) { controller.enqueue("Data chunk 1\n"); controller.enqueue("Data chunk 2\n"); controller.close(); } }); return new Response(stream, { headers: {"content-type": "text/plain"} }); } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const stream1 = await fetch("https://resource1.example.com").then(res => res.body); const stream2 = await fetch("https://resource2.example.com").then(res => res.body); const mergedStream = new ReadableStream({ async start(controller) { const reader1 = stream1.getReader(); const reader2 = stream2.getReader(); while (true) { const { done: done1, value: value1 } = await reader1.read(); if (value1) controller.enqueue(value1); if (done1) break; } while (true) { const { done: done2, value: value2 } = await reader2.read(); if (value2) controller.enqueue(value2); if (done2) break; } controller.close(); } }); return new Response(mergedStream, { headers: {"content-type": "text/plain"} }); } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const response = await fetch(request); const integrity = btoa("some-secret-content"); // Example: calculate integrity const newHeaders = new Headers(response.headers); newHeaders.set("Content-Security-Policy", `object-src 'none'; script-src 'self' 'sha256-${integrity}'`); return new Response(response.body, { status: response.status, headers: newHeaders }); } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const url = new URL(request.url); const originalUrl = url.searchParams.get("url"); if (!originalUrl) { return new Response("Missing URL parameter", { status: 400 }); } try { const resourceResponse = await fetch(originalUrl); if (!resourceResponse.ok) { throw new Error(`Failed to fetch: ${resourceResponse.statusText}`); } const m3u8Content = await resourceResponse.text(); // Example: Modify m3u8 content for custom URLs or add authentication tokens const modifiedM3u8 = m3u8Content.replace(/=\/media\//g, `=\/media\/secure?token=YOUR_TOKEN&url=`); return new Response(modifiedM3u8, { status: 200, headers: {"Content-Type": "application/vnd.apple.mpegurl"} }); } catch (error) { console.error("Error processing m3u8:", error); return new Response(`Error: ${error.message}`, { status: 500 }); } } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const url = new URL(request.url); const imageUrl = url.searchParams.get("image"); if (!imageUrl) { return new Response("Missing image URL parameter", { status: 400 }); } try { const response = await fetch(imageUrl); if (!response.ok) { throw new Error(`Failed to fetch image: ${response.statusText}`); } const imageBlob = await response.blob(); const imageBitmap = await createImageBitmap(imageBlob); // Get dimensions const originalWidth = imageBitmap.width; const originalHeight = imageBitmap.height; // Determine target size based on device pixel ratio or viewport width (simplified) const dpr = window.devicePixelRatio || 1; // In a real scenario, you'd get this from the request headers or JS const maxWidth = originalWidth / dpr; // Example: reduce size for higher DPR screens const maxHeight = originalHeight / dpr; let targetWidth = originalWidth; let targetHeight = originalHeight; if (originalWidth > maxWidth) { targetWidth = maxWidth; targetHeight = (originalHeight * maxWidth) / originalWidth; } if (targetHeight > maxHeight) { targetHeight = maxHeight; targetWidth = (originalWidth * maxHeight) / originalHeight; } // Draw image to a canvas with new dimensions const canvas = new OffscreenCanvas(targetWidth, targetHeight); const ctx = canvas.getContext('2d'); ctx.drawImage(imageBitmap, 0, 0, targetWidth, targetHeight); const resizedBlob = await canvas.convertToBlob({ type: response.headers.get('content-type') || 'image/jpeg', quality: 0.8 // Adjust quality as needed }); return new Response(resizedBlob, { status: 200, headers: { 'Content-Type': resizedBlob.type, 'X-Image-Resized': 'true' } }); } catch (error) { console.error("Error resizing image:", error); return new Response(`Error resizing image: ${error.message}`, { status: 500 }); } } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const url = new URL(request.url); const imageUrl = url.searchParams.get("image"); if (!imageUrl) { return new Response("Missing image URL parameter", { status: 400 }); } try { const response = await fetch(imageUrl); if (!response.ok) { throw new Error(`Failed to fetch image: ${response.statusText}`); } const imageBlob = await response.blob(); const imageBitmap = await createImageBitmap(imageBlob); // Determine target format (e.g., WebP if supported by browser) const acceptHeader = request.headers.get('accept') || ''; let targetMimeType = response.headers.get('content-type') || 'image/jpeg'; if (acceptHeader.includes('image/webp') && targetMimeType !== 'image/gif') { targetMimeType = 'image/webp'; } // Convert to target format const canvas = new OffscreenCanvas(imageBitmap.width, imageBitmap.height); const ctx = canvas.getContext('2d'); ctx.drawImage(imageBitmap, 0, 0); const convertedBlob = await canvas.convertToBlob({ type: targetMimeType, quality: 0.8 // Adjust quality as needed }); return new Response(convertedBlob, { status: 200, headers: { 'Content-Type': convertedBlob.type, 'X-Image-Converted': convertedBlob.type } }); } catch (error) { console.error("Error converting image:", error); return new Response(`Error converting image: ${error.message}`, { status: 500 }); } } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const referer = request.headers.get("Referer"); const allowedReferers = ["https://www.example.com", "https://sub.example.com"]; // Add your allowed referers let isAllowed = false; if (referer) { for (const allowed of allowedReferers) { if (referer.startsWith(allowed)) { isAllowed = true; break; } } } if (!isAllowed) { // Return a placeholder image or an error response return new Response("Access Denied: Unauthorized Referer", { status: 403, headers: {"Content-Type": "text/plain"} }); } return fetch(request); } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const secret = "YOUR_SUPER_SECRET_KEY"; // In a real scenario, fetch this securely const authHeader = request.headers.get("Authorization"); if (!authHeader) { return new Response("Authorization header missing", { status: 401, headers: {"WWW-Authenticate": "Bearer"} }); } const token = authHeader.split(" ")[1]; if (!token) { return new Response("Invalid Authorization header format", { status: 401 }); } // In a real scenario, you would verify the token against a known secret or token issuer // For this example, we'll just compare it directly (highly insecure for production) if (token !== secret) { return new Response("Invalid token", { status: 403 }); } // If token is valid, proceed to fetch the original resource return fetch(request); } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const url = new URL(request.url); const filename = url.searchParams.get("file") || "download.bin"; // Default filename const response = await fetch(request); const contentDisposition = `attachment; filename="${filename}"`; const newHeaders = new Headers(response.headers); newHeaders.set("Content-Disposition", contentDisposition); return new Response(response.body, { status: response.status, headers: newHeaders }); } ``` ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { // The CF-Connecting-IP header is typically added by Cloudflare // EdgeOne might use a similar header, check their documentation const clientIP = request.headers.get("CF-Connecting-IP") || request.headers.get("X-Forwarded-For") || "Unknown"; // You can log this IP, use it in headers, or return it in a response console.log("Client IP Address:", clientIP); // Example: Add the client IP to a custom response header const response = await fetch(request); const newHeaders = new Headers(response.headers); newHeaders.set("X-Client-IP", clientIP); return new Response(response.body, { status: response.status, headers: newHeaders }); } ``` -------------------------------- ### Enable HTTP/3 (QUIC) with EdgeOne Source: https://edgeone.ai/document/zh/56978 This section details how to enable HTTP/3 (QUIC) support on EdgeOne. It covers the overview, enabling the feature, and provides access to the QUIC SDK for integration. The SDK guide includes download, integration instructions, code examples for Android and iOS, and API documentation for both platforms. ```plaintext Overview Enable HTTP/3 QUIC SDK SDK Overview SDK Download and Integration Guide Code Examples Android iOS API Documentation Android iOS ``` -------------------------------- ### Edge Function Examples Source: https://edgeone.ai/document/zh/overview A collection of example Edge Functions demonstrating various functionalities. These examples cover returning different response types (HTML, JSON), fetching remote resources, authentication, modifying headers, A/B testing, setting cookies, redirection, cache API usage, streaming responses, anti-tampering, image optimization, and more. ```javascript addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }); async function handleRequest(request) { // Example: Return an HTML page return new Response('

Hello from Edge Function!

', { headers: { 'content-type': 'text/html' } }); } ``` -------------------------------- ### Terraform Configuration for EdgeOne Source: https://edgeone.ai/document/zh/45963 Information on using Terraform to manage EdgeOne resources. It covers Terraform introduction, installation, configuration, and provides examples for setting up site acceleration and the rule engine. ```hcl terraform { required_providers { edgeone = { source = "cloudflare/edgeone" version = "~> 1.0" } } } provider "edgeone" { # Configuration options for the EdgeOne provider } resource "edgeone_site" "example" { name = "example-site" # Other site configuration... } resource "edgeone_rule_engine_rule" "example" { zone_id = edgeone_site.example.id description = "Example rule" expression = "(http.request.uri.path contains \"/api\")" action = "" // Action configuration... } ``` -------------------------------- ### Edge Function Examples for Image Optimization Source: https://edgeone.ai/document/zh/56978 This snippet showcases examples of Edge Functions designed for image optimization. It includes functionalities for adaptive image format conversion (e.g., to WebP) and adaptive scaling, helping to reduce bandwidth and improve loading times. These examples demonstrate how to leverage Edge Functions for dynamic image processing at the edge. ```javascript // Example for adaptive image format conversion (e.g., to WebP) // This function would typically inspect the request headers (like Accept) and // transform the image format on the fly. addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }); async function handleRequest(request) { const url = new URL(request.url); const imageName = url.pathname.substring(1); // Fetch the original image const response = await fetch(request); let image = await response.arrayBuffer(); // Check if the client supports WebP const acceptHeader = request.headers.get('accept'); if (acceptHeader && acceptHeader.includes('image/webp')) { // Placeholder for actual image conversion logic (e.g., using a WebAssembly module) // In a real scenario, you'd use a library or service to convert the image to WebP. console.log('Converting image to WebP...'); // For demonstration, we'll just return the original image. // image = convertToWebP(image); // Replace with actual conversion } return new Response(image, { headers: { 'Content-Type': 'image/jpeg', // Or the appropriate content type 'Cache-Control': 'public, max-age=3600' } }); } // Placeholder for actual image conversion function // function convertToWebP(imageData) { // // ... implementation to convert imageData to WebP format ... // return imageData; // } ``` ```javascript // Example for adaptive image scaling // This function resizes images based on a query parameter (e.g., ?width=300) addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }); async function handleRequest(request) { const url = new URL(request.url); const desiredWidth = parseInt(url.searchParams.get('width')); if (desiredWidth) { // Fetch the original image const response = await fetch(request); let image = await response.arrayBuffer(); // Placeholder for actual image resizing logic // In a real scenario, you'd use a library or service to resize the image. console.log(`Resizing image to width: ${desiredWidth}`); // image = resizeImage(image, desiredWidth); // Replace with actual resizing return new Response(image, { headers: { 'Content-Type': 'image/jpeg', // Or the appropriate content type 'Cache-Control': 'public, max-age=3600' } }); } else { // If no width parameter, return the original image return fetch(request); } } // Placeholder for actual image resizing function // function resizeImage(imageData, width) { // // ... implementation to resize imageData to the specified width ... // return imageData; // } ``` -------------------------------- ### Edge Function: Get Client IP Example Source: https://edgeone.ai/document/zh/46151 An Edge Function example that retrieves the client's IP address from common headers forwarded by EdgeOne or the origin server. ```javascript addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { // EdgeOne often forwards the client IP in headers like X-Forwarded-For or CF-Connecting-IP. // The exact header might depend on configuration. const clientIp = request.headers.get('X-Forwarded-For') || request.headers.get('CF-Connecting-IP') || request.headers.get('X-Real-IP') || 'Unknown IP'; // If the header contains multiple IPs (e.g., X-Forwarded-For), take the first one. const ipAddress = clientIp.split(',')[0].trim(); const htmlContent = ` Client IP

Your IP Address: ${ipAddress}

`; return new Response(htmlContent, { headers: { 'Content-Type': 'text/html', }, }); } ``` -------------------------------- ### Edge Function: Get Client IP Example Source: https://edgeone.ai/document/zh/53372 This Edge Function example shows how to retrieve the client's IP address. It prioritizes common headers used by CDNs and proxies. ```JavaScript addEventListener('fetch', event => { const headers = event.request.headers; const ip = headers.get('CF-Connecting-IP') || // Cloudflare headers.get('X-Forwarded-For') || // Proxies headers.get('X-Real-IP') || // Nginx event.request.remoteAddr; // Direct connection (may not be available) event.respondWith(new Response(`Your IP address is: ${ip}`, { headers: { 'Content-Type': 'text/plain' } })); }); ``` -------------------------------- ### EdgeOne QUIC SDK Integration Example Source: https://edgeone.ai/document/zh/56251 Provides example code for integrating the QUIC SDK for HTTP/3 support. This helps in enabling faster and more reliable connections by leveraging the QUIC protocol. ```android This section would contain Android-specific code examples for QUIC SDK integration. ``` ```ios This section would contain iOS-specific code examples for QUIC SDK integration. ``` -------------------------------- ### iOS QUIC SDK Integration Example Source: https://edgeone.ai/document/zh/45961 Provides an example of integrating the QUIC SDK for iOS, demonstrating how to enable HTTP/3 support. This involves adding the SDK to your Xcode project and initializing it. ```swift // iOS // 1. Add the QUIC SDK to your project using Swift Package Manager or by dragging the framework. // Example using Swift Package Manager: // File -> Add Packages... -> Enter the package URL. // 2. Import the QUIC module in your Swift file: // import QUIC // 3. Initialize the QUIC SDK. This can be done in your AppDelegate or SceneDelegate: // QUICManager.shared.initialize { // print("QUIC SDK initialized successfully.") // } onError: { // errorCode, errorMessage in // print("QUIC SDK initialization failed: \(errorCode), \(errorMessage)") // } // 4. Use the QUIC SDK for network requests. Example using URLSession with QUIC support: // var urlRequest = URLRequest(url: URL(string: "https://your-edgeone-domain.com/resource")!) // urlRequest.httpMethod = "GET" // // let configuration = URLSessionConfiguration.default // configuration.protocolClasses?.insert(QUICProtocolHandler.self, at: 0) // let session = URLSession(configuration: configuration) // // let task = session.dataTask(with: urlRequest) { // data, response, error in // if let error = error { // print("Error making request: \(error.localizedDescription)") // return // } // if let httpResponse = response as? HTTPURLResponse { // print("Response received with status code: \(httpResponse.statusCode)") // if let responseData = data { // print("Response body: \(String(data: responseData, encoding: .utf8) ?? "")") // } // } // } // task.resume() ``` -------------------------------- ### Edge Function: Get Client IP Example Source: https://edgeone.ai/document/zh/45961 An Edge Function example that retrieves and returns the client's IP address. It commonly uses headers like 'CF-Connecting-IP' (if behind Cloudflare) or similar headers provided by the CDN. -------------------------------- ### Edge Functions - Getting Client IP Example Source: https://edgeone.ai/document/zh/55640 This Edge Function example shows how to retrieve the client's IP address. It typically relies on specific headers provided by the CDN or edge network, such as `CF-Connecting-IP` (Cloudflare) or `X-Forwarded-For`. ```javascript addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { // Common headers to get client IP, order might matter depending on proxy setup const clientIp = [ request.headers.get('CF-Connecting-IP'), // Cloudflare specific request.headers.get('X-Forwarded-For'), // Standard header, may contain multiple IPs request.headers.get('X-Real-IP') // Another common header ].find(ip => ip); let responseBody = `Your IP Address is: ${clientIp || 'Unknown'}`; // If X-Forwarded-For contains multiple IPs, the first one is usually the client's if (clientIp && clientIp.includes(',')) { responseBody = `Your IP Address is: ${clientIp.split(',')[0].trim()}`; } return new Response(responseBody, { headers: { 'content-type': 'text/plain;charset=UTF-8', }, }); } ``` -------------------------------- ### Edge Function: Fetch Remote Resource Example Source: https://edgeone.ai/document/zh/54506 Demonstrates how an Edge Function can fetch resources from a remote URL. This allows for dynamic content retrieval and manipulation at the edge. The example uses the `fetch` API to get data from an external source. ```javascript addEventListener('fetch', (event) => { event.respondWith(fetch('https://api.example.com/data').then(response => { return response; })); }); ``` -------------------------------- ### Edge Function: Cache POST Request Example Source: https://edgeone.ai/document/zh/54506 Explains how to cache POST requests using an Edge Function. While POST requests are typically not cacheable by default, this example shows a pattern to cache them based on specific criteria or by transforming them into cacheable GET requests if appropriate. ```javascript addEventListener('fetch', (event) => { if (event.request.method === 'POST') { // Handle POST request, potentially cacheable based on logic // For example, transforming it or caching based on body hash event.respondWith(fetch(event.request)); } else { // Handle other methods using cache as usual event.respondWith(caches.match(event.request).then(response => { if (response) return response; return fetch(event.request).then(res => { caches.open('my-cache').then(cache => cache.put(event.request.url, res.clone())); return res; }); })); } }); ``` -------------------------------- ### Android QUIC SDK Integration Example Source: https://edgeone.ai/document/zh/45961 Provides an example of integrating the QUIC SDK for Android, demonstrating how to enable HTTP/3 support. This requires the QUIC SDK library to be included in the Android project. ```java // Android // 1. Add the dependency to your app's build.gradle file: // implementation 'com.tencent.edgeone:quicsdk:+' // 2. Initialize the QUIC SDK in your Application class or main Activity: // QUIC.initialize(this, new QUIC.InitCallback() { // @Override // public void onInitialized() { // Log.d("QUIC", "QUIC SDK initialized successfully."); // } // @Override // public void onError(int errorCode, String errorMessage) { // Log.d("QUIC", "QUIC SDK initialization failed: " + errorCode + ", " + errorMessage); // } // }); // 3. Use the QUIC SDK to make network requests. For example, using OkHttp with QUIC support: // OkHttpClient client = new OkHttpClient.Builder() // .protocols(Arrays.asList(Protocol.QUIC, Protocol.HTTP_1_1)) // .build(); // Request request = new Request.Builder() // .url("https://your-edgeone-domain.com/resource") // .build(); // try (Response response = client.newCall(request).execute()) { // // Process the response // Log.d("QUIC", "Response received: " + response.body().string()); // } catch (IOException e) { // Log.e("QUIC", "Error making request: " + e.getMessage()); // } ``` -------------------------------- ### Edge Functions - Streaming Response Example Source: https://edgeone.ai/document/zh/55640 This Edge Function example demonstrates how to create a streaming response. It uses `ReadableStream` to send data incrementally to the client, which is efficient for large responses or real-time data feeds. This allows the client to start processing data before the entire response is generated. ```javascript addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const stream = new ReadableStream({ async start(controller) { controller.enqueue('Chunk 1: Hello\n'); await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate delay controller.enqueue('Chunk 2: World!\n'); await new Promise(resolve => setTimeout(resolve, 1000)); controller.enqueue('Chunk 3: End.\n'); controller.close(); } }); return new Response(stream, { headers: { 'content-type': 'text/plain;charset=UTF-8', }, }); } ``` -------------------------------- ### Android QUIC SDK Integration Example Source: https://edgeone.ai/document/zh/56724 This section provides an example of how to integrate the QUIC SDK for Android. It demonstrates the necessary steps for downloading and integrating the SDK into an Android project to leverage HTTP/3 (QUIC) protocol for faster and more reliable connections. ```java import com.tencent.qcloud.quicsdk.impl.QuicManager; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize QuicManager with application context QuicManager.init(getApplicationContext()); // Example of using QuicManager (specific API usage would depend on SDK documentation) // For instance, configuring connection settings or initiating a connection. // ... } } ``` -------------------------------- ### Edge Function: Get Client IP Example Source: https://edgeone.ai/document/zh/54200 Retrieves the client's IP address from the request headers, which is often forwarded by EdgeOne. This is useful for logging or geo-targeting. ```javascript addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }); async function handleRequest(request) { // EdgeOne typically forwards the client IP in CF-Connecting-IP header const clientIp = request.headers.get('CF-Connecting-IP') || request.headers.get('X-Forwarded-For'); if (!clientIp) { return new Response('Could not determine client IP', { status: 400, }); } const data = { message: `Hello, your IP is ${clientIp}`, clientIp: clientIp }; return new Response(JSON.stringify(data), { headers: { 'content-type': 'application/json' }, }); } ``` -------------------------------- ### Edge Functions: Get Client IP Example Source: https://edgeone.ai/document/zh/54764 Demonstrates how to retrieve the client's IP address within an Edge Function. This is often needed for logging, rate limiting, or geolocation. ```javascript addEventListener('fetch', (event) => { event.respondWith(handleRequest(event)); }); async function handleRequest(event) { // EdgeOne typically provides the client IP in a header like 'CF-Connecting-IP' // or 'X-Forwarded-For'. Check your specific EdgeOne configuration. const clientIP = event.request.headers.get('CF-Connecting-IP') || event.request.headers.get('X-Forwarded-For'); if (clientIP) { return new Response(`Your IP address is: ${clientIP}`); } else { return new Response('Could not determine client IP address.'); } } ``` -------------------------------- ### iOS QUIC SDK Integration Example Source: https://edgeone.ai/document/zh/56724 This section provides an example of how to integrate the QUIC SDK for iOS. It outlines the process for downloading and integrating the SDK into an iOS project to enable HTTP/3 (QUIC) protocol support, enhancing connection performance. ```swift import QuicSDK class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Initialize QuicManager (specific API usage would depend on SDK documentation) // For example, setting up configurations or starting services. // QuicManager.shared.configure(...) // ... } } ``` -------------------------------- ### Terraform Configuration Examples Source: https://edgeone.ai/document/zh/56251 Demonstrates how to use Terraform to automate the configuration of EdgeOne services, including site acceleration and rules engine settings. This enables Infrastructure as Code (IaC) practices. ```hcl provider "edgeone" { // your EdgeOne provider configuration } resource "edgeone_site" "example_site" { site_name = "my-accelerated-site" domains = ["example.com"] // other site configuration } resource "edgeone_rule_engine" "example_rule" { site_id = edgeone_site.example_site.id rules = [ { action = "CACHE" match = { "request.uri.path" = "*.jpg" } } ] } ``` -------------------------------- ### Android QUIC SDK Integration Example Source: https://edgeone.ai/document/zh/53372 This snippet demonstrates how to integrate the QUIC SDK for Android to enable HTTP/3 support. It outlines the basic steps for downloading and integrating the SDK into an Android project. ```Java import com.tencent.edgeone.quic.QUICManager; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize QUICManager with your application context QUICManager.initialize(this); // You can now use QUICManager for HTTP/3 requests // Example: Make a request to a URL that supports HTTP/3 // QUICManager.performRequest("https://your-http3-enabled-domain.com"); } } ``` -------------------------------- ### Android QUIC SDK Integration Example Source: https://edgeone.ai/document/zh/46151 Example code for integrating the QUIC SDK for Android to enable HTTP/3 (QUIC) access. This involves downloading and integrating the SDK into your Android project. ```java String quicSdkVersion = "1.0.0"; String quicSdkUrl = "https://example.com/sdk/quic-android.aar"; // Add this to your app's build.gradle file: // implementation "com.edgeone.quic:sdk:$quicSdkVersion" // Or download and include manually: // File sdkFile = new File(Environment.getExternalStorageDirectory(), "quic-android.aar"); // implementation files(sdkFile.getAbsolutePath()) // Basic usage within an Activity: public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize QUIC SDK (example) // QUICManager.initialize(this); // Make a QUIC request (example) // QUICClient.sendRequest("https://your-edgeone-domain.com", new QUICResponseCallback() { // @Override // public void onSuccess(String response) { // Log.d("QUIC", "Response: " + response); // } // // @Override // public void onFailure(Exception e) { // Log.e("QUIC", "Error: ", e); // } // }); } } ``` -------------------------------- ### Edge Functions: Example - Get Client IP Source: https://edgeone.ai/document/zh/45962 Shows how to access and log the client's IP address within an Edge Function. The IP is typically provided in a specific header by the EdgeOne platform. ```javascript addEventListener('fetch', event => { // The header containing the client IP can vary. Common ones include 'X-Forwarded-For', 'CF-Connecting-IP', etc. // Check EdgeOne documentation for the specific header they use. const clientIp = event.request.headers.get('X-Forwarded-For') || event.request.headers.get('CF-Connecting-IP') || 'unknown'; console.log(`Request received from IP: ${clientIp}`); // You can then use this IP for logging, geo-targeting, or access control. const response = new Response(`Your IP: ${clientIp}`, { headers: { 'content-type': 'text/plain' } }); event.respondWith(response); }); ``` -------------------------------- ### Edge Function: Get Client IP Example Source: https://edgeone.ai/document/zh/56724 Shows how to retrieve the client's IP address within an Edge function. It typically relies on specific headers provided by the CDN or proxy, such as `CF-Connecting-IP` or `X-Forwarded-For`. ```javascript addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { // Try common headers that contain the client's IP address const clientIP = request.headers.get('CF-Connecting-IP') || // Cloudflare request.headers.get('X-Forwarded-For') || // Standard proxy header request.headers.get('X-Real-IP'); // Another common proxy header let responseBody = 'Client IP not detected.'; if (clientIP) { // X-Forwarded-For can contain multiple IPs, take the first one (usually the original client) const ipAddress = clientIP.split(',')[0].trim(); responseBody = `Your IP address is: ${ipAddress}`; } return new Response(responseBody, { headers: { 'content-type': 'text/plain', }, }); } ``` -------------------------------- ### Edge Function: Get Client IP Example Source: https://edgeone.ai/document/zh/54506 Demonstrates how to retrieve the client's IP address within an Edge Function. It utilizes common headers like `CF-Connecting-IP` or `X-Forwarded-For` that are often added by edge networks. ```javascript addEventListener('fetch', (event) => { const clientIp = event.request.headers.get('CF-Connecting-IP') || event.request.headers.get('X-Forwarded-For'); let responseBody = `Your IP address is: ${clientIp || 'unknown'}`; event.respondWith(new Response(responseBody, { headers: { 'Content-Type': 'text/plain', }, })); }); ```