Skip to content

Commit

Permalink
Add advanced code example to documentation (#3026)
Browse files Browse the repository at this point in the history
* Add advanced code example

* Update templates/experimental/worker-rust/README.md

Co-authored-by: Jacob M-G Evans <[email protected]>

* Run Prettier

* Change Example

* Update README.md

Add link to workers-rs

* Fix README.md formatting

---------

Co-authored-by: Jacob M-G Evans <[email protected]>
  • Loading branch information
Alex1607 and JacobMGEvans authored Nov 15, 2023
1 parent 3753eaf commit 46a35e0
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions templates/experimental/worker-rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,41 @@ $ npm run deploy

Read the latest `worker` crate documentation here: https://docs.rs/worker

## Advanced Example

As this template comprises only the essential setup, we recommend considering our advanced example to leverage its additional functionalities. The advanced example showcases the creation of multiple routes, logging of requests, retrieval of field data from a form, and other features that may prove useful to your project.
The following example has been taken from: [workers-rs](https://github.com/cloudflare/workers-rs). You can learn more about how to use workers with rust by going there.

```rust
use worker::*;

#[event(fetch)]
pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Response> {
console_log!(
"{} {}, located at: {:?}, within: {}",
req.method().to_string(),
req.path(),
req.cf().coordinates().unwrap_or_default(),
req.cf().region().unwrap_or("unknown region".into())
);

if !matches!(req.method(), Method::Post) {
return Response::error("Method Not Allowed", 405);
}

if let Some(file) = req.form_data().await?.get("file") {
return match file {
FormEntry::File(buf) => {
Response::ok(&format!("size = {}", buf.bytes().await?.len()))
}
_ => Response::error("`file` part of POST form must be a file", 400),
};
}

Response::error("Bad Request", 400)
}
```

## WebAssembly

`workers-rs` (the Rust SDK for Cloudflare Workers used in this template) is meant to be executed as compiled WebAssembly, and as such so **must** all the code you write and depend upon. All crates and modules used in Rust-based Workers projects have to compile to the `wasm32-unknown-unknown` triple.
Expand Down

0 comments on commit 46a35e0

Please sign in to comment.