Skip to content

Commit

Permalink
headers too
Browse files Browse the repository at this point in the history
  • Loading branch information
j-white committed May 7, 2024
1 parent 2ab5659 commit 80b5280
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,23 @@ mod metrics;
#[worker::send]
pub async fn do_fetch(
url: String,
headers: String,
data: Option<JsValue>,
) -> Result<Response> {
let mut http_headers = Headers::new();
// split headers by command, and then by =
for header in headers.split(",") {
let parts: Vec<&str> = header.split("=").collect();
if parts.len() == 2 {
let key = parts[0].trim();
let value = parts[1].trim();
http_headers.set(key, value).expect("failed to construct header");
}
}

let mut init = RequestInit::new();
init.method = Method::Post;
init.with_body(data);
init.with_body(data).with_headers(http_headers);
Fetch::Request(Request::new_with_init(url.as_str(), &init)?)
.send()
.await
Expand All @@ -27,6 +39,10 @@ async fn main(_req: Request, env: Env, _ctx: Context) -> Result<Response> {
let cloudflare_api_url = env.var("CLOUDFLARE_API_URL")?.to_string();
let cloudflare_api_key = env.var("CLOUDFLARE_API_KEY")?.to_string();
let cloudflare_account_id = env.var("CLOUDFLARE_ACCOUNT_ID")?.to_string();
let otlp_headers = match env.var("OTLP_HEADERS") {
Ok(val) => val.to_string(),
Err(_) => String::from(""),
};

let end = chrono::Utc::now();
let start = end - chrono::Duration::minutes(1);
Expand Down Expand Up @@ -61,6 +77,6 @@ async fn main(_req: Request, env: Env, _ctx: Context) -> Result<Response> {
};
let metrics = MetricsData::from(&mut resource_metrics);
let metrics_json = serde_json::to_string(&metrics).unwrap();
let response = do_fetch(metrics_url, Some(JsValue::from_str(&metrics_json)).into()).await?;
let response = do_fetch(metrics_url, otlp_headers, Some(JsValue::from_str(&metrics_json)).into()).await?;
return Ok(response);
}
1 change: 1 addition & 0 deletions wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ build = { command = "cargo install -q worker-build && worker-build --dev" }

[env.dev.vars]
METRICS_URL = "http://collector:4318/v1/metrics"
OTLP_HEADERS = "Authorization=Basic <base64 instanceID:token>"
CLOUDFLARE_API_URL = "https://api.cloudflare.com/client/v4/graphql"
CLOUDFLARE_API_KEY = "fake"
CLOUDFLARE_ACCOUNT_ID = "1234"

0 comments on commit 80b5280

Please sign in to comment.