import os
import requests
account_id = os.environ["CLOUDFLARE_ACCOUNT_ID"]
script_name = os.environ["CLOUDFLARE_SCRIPT_NAME"]
auth_token = os.environ["CLOUDFLARE_API_TOKEN"]
url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts/{script_name}"
headers = {
"Authorization": f"Bearer {auth_token}",
"Content-Type": "application/javascript"
}
body = 'addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })'
response = requests.post(url, headers=headers, data=body)
if response.status_code >= 400:
print(f"Error: {response.status_code} - {response.text}")
else:
print(response.text)
import os
import httpx
account_id = os.environ["CLOUDFLARE_ACCOUNT_ID"]
script_name = os.environ["CLOUDFLARE_SCRIPT_NAME"]
auth_token = os.environ["CLOUDFLARE_API_TOKEN"]
url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts/{script_name}"
headers = {
"Authorization": f"Bearer {auth_token}",
"Content-Type": "application/javascript"
}
body = 'addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })'
try:
response = httpx.post(url, headers=headers, data=body)
response.raise_for_status()
print(response.text)
except httpx.HTTPStatusError as e:
print(f"Error: {e.response.status_code} - {e.response.text}")
const fetch = require('node-fetch');
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID;
const scriptName = process.env.CLOUDFLARE_SCRIPT_NAME;
const authToken = process.env.CLOUDFLARE_API_TOKEN;
const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${scriptName}`;
const headers = {
'Authorization': `Bearer ${authToken}`,
'Content-Type': 'application/javascript'
};
const body = 'addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })';
fetch(url, {
method: 'POST',
headers,
body
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.text();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
const axios = require('axios');
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID;
const scriptName = process.env.CLOUDFLARE_SCRIPT_NAME;
const authToken = process.env.CLOUDFLARE_API_TOKEN;
const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${scriptName}`;
const headers = {
'Authorization': `Bearer ${authToken}`,
'Content-Type': 'application/javascript'
};
const body = 'addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })';
axios.post(url, body, { headers })
.then(response => {
if (response.status >= 400) {
throw new Error(`HTTP error! status: ${response.status}`);
}
console.log(response.data);
})
.catch(error => console.error('Error:', error.message));
package main
import (
"fmt"
"io"
"net/http"
"os"
)
func main() {
accountId := os.Getenv("CLOUDFLARE_ACCOUNT_ID")
scriptName := os.Getenv("CLOUDFLARE_SCRIPT_NAME")
authToken := os.Getenv("CLOUDFLARE_API_TOKEN")
url := fmt.Sprintf("https://api.cloudflare.com/client/v4/accounts/%s/workers/scripts/%s", accountId, scriptName)
body := `addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })`
req, err := http.NewRequest("POST", url, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
req.Header.Set("Authorization", "Bearer "+authToken)
req.Header.Set("Content-Type", "application/javascript")
req.Body = io.NopCloser(strings.NewReader(body))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error making request:", err)
return
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Error: %d - %s\n", resp.StatusCode, string(body))
return
}
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
<?php
$accountId = getenv('CLOUDFLARE_ACCOUNT_ID');
$scriptName = getenv('CLOUDFLARE_SCRIPT_NAME');
$authToken = getenv('CLOUDFLARE_API_TOKEN');
$url = "https://api.cloudflare.com/client/v4/accounts/{$accountId}/workers/scripts/{$scriptName}";
$headers = [
'Authorization: Bearer ' . $authToken,
'Content-Type: application/javascript'
];
$body = 'addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
echo "Error: {$httpCode} - {$response}\n";
} else {
echo $response;
}
require 'net/http'
require 'json'
account_id = ENV['CLOUDFLARE_ACCOUNT_ID']
script_name = ENV['CLOUDFLARE_SCRIPT_NAME']
auth_token = ENV['CLOUDFLARE_API_TOKEN']
uri = URI.parse("https://api.cloudflare.com/client/v4/accounts/#{account_id}/workers/scripts/#{script_name}")
req = Net::HTTP::Post.new(uri)
req['Authorization'] = "Bearer #{auth_token}"
req['Content-Type'] = 'application/javascript'
req.body = 'addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })'
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
response = http.request(req)
if response.code.to_i >= 400
puts "Error: #{response.code} - #{response.body}"
else
puts response.body
end
import Foundation
let accountId = ProcessInfo.processInfo.environment["CLOUDFLARE_ACCOUNT_ID"] ?? ""
let scriptName = ProcessInfo.processInfo.environment["CLOUDFLARE_SCRIPT_NAME"] ?? ""
let authToken = ProcessInfo.processInfo.environment["CLOUDFLARE_API_TOKEN"] ?? ""
let url = URL(string: "https://api.cloudflare.com/client/v4/accounts/" + accountId + "/workers/scripts/" + scriptName)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer " + authToken, forHTTPHeaderField: "Authorization")
request.setValue("application/javascript", forHTTPHeaderField: "Content-Type")
let body = "addEventListener(\"fetch\", event => { event.respondWith(new Response(\"Hello\")) })"
request.httpBody = body.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error)")
return
}
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 400 else {
if let data = data, let responseBody = String(data: data, encoding: .utf8) {
print(responseBody)
}
return
}
if let data = data, let responseBody = String(data: data, encoding: .utf8) {
print("Error: \(httpResponse.statusCode) - \(responseBody)")
}
}
task.resume()
RunLoop.main.run()
use std::env;
use reqwest::blocking::Client;
use reqwest::header;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let account_id = env::var("CLOUDFLARE_ACCOUNT_ID")?;
let script_name = env::var("CLOUDFLARE_SCRIPT_NAME")?;
let auth_token = env::var("CLOUDFLARE_API_TOKEN")?;
let url = format!(
"https://api.cloudflare.com/client/v4/accounts/{}/workers/scripts/{}",
account_id, script_name
);
let client = Client::new();
let mut headers = header::HeaderMap::new();
headers.insert(
"Authorization",
format!("Bearer {}", auth_token).parse()?,
);
headers.insert(
"Content-Type",
"application/javascript".parse()?,
);
let body = "addEventListener(\"fetch\", event => { event.respondWith(new Response(\"Hello\")) })";
let response = client
.post(&url)
.headers(headers)
.body(body.to_string())
.send()?;
if !response.status().is_success() {
eprintln!(
"Error: {} - {}",
response.status(),
response.text()?
);
} else {
println!("{}", response.text()?);
}
Ok(())
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var accountId = Environment.GetEnvironmentVariable("CLOUDFLARE_ACCOUNT_ID");
var scriptName = Environment.GetEnvironmentVariable("CLOUDFLARE_SCRIPT_NAME");
var authToken = Environment.GetEnvironmentVariable("CLOUDFLARE_API_TOKEN");
var url = $"https://api.cloudflare.com/client/v4/accounts/{accountId}/workers/scripts/{scriptName}";
var body = "addEventListener(\"fetch\", event => { event.respondWith(new Response(\"Hello\")) })";
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken);
client.DefaultRequestHeaders.Add("Content-Type", "application/javascript");
var response = await client.PostAsync(url, new StringContent(body));
if (!response.IsSuccessStatusCode)
{
var errorContent = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Error: {response.StatusCode} - {errorContent}");
}
else
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
}