Skip to content

Automatically bind Cloudflare Workers bindings in `wrangler.toml` to Rust struct

License

Notifications You must be signed in to change notification settings

ohkami-rs/worker-bindings

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

worker-bindings

Automatically bind bindings in your `wrangler.toml` into a Rust struct

test status of worker-bindings crates.io

Example

wrangler.toml

[vars]
MY_VAR = "my-variable"

[[kv_namespaces]]
binding = "MY_KV"
id      = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

lib.rs

use worker::*;
use worker_bindings::bindings;

/* This knows all your bindings in wrangler.toml */
#[bindings]
struct Bindings;

#[event(fetch)]
pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Response> {
    /* load bindings from env */
    let b = Bindings::from(&env);

    let var: &'static str = b.MY_VAR;

    let data = b.MY_KV.get("data").text().await?;

    //...
}

Note

  • #[bindings] works in a cargo workspace but has a limitation that it fails to resolve wrangler.toml if more than one members have wrangler.tomls.
  • This crate is originally developed in Ohkami web framework and later extracted as an independent edition.

License

worker-bindings is licensed under the MIT License (LICENSE or https://opensource.org/licenses/MIT).