File
Blob: samples/hello-wasm/src/lib.rs
| 1 | use worker::*; |
| 2 | |
| 3 | mod utils; |
| 4 | |
| 5 | fn log_request(req: &Request) { |
| 6 | console_log!( |
| 7 | "{} - [{}], located at: {:?}, within: {}", |
| 8 | Date::now().to_string(), |
| 9 | req.path(), |
| 10 | req.cf().unwrap().coordinates().unwrap_or_default(), |
| 11 | req.cf() |
| 12 | .unwrap() |
| 13 | .region() |
| 14 | .unwrap_or_else(|| "unknown region".into()) |
| 15 | ); |
| 16 | } |
| 17 | |
| 18 | #[event(fetch)] |
| 19 | pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Response> { |
| 20 | log_request(&req); |
| 21 | |
| 22 | // Optionally, get more helpful error messages written to the console in the case of a panic. |
| 23 | utils::set_panic_hook(); |
| 24 | |
| 25 | // Optionally, use the Router to handle matching endpoints, use ":name" placeholders, or "*name" |
| 26 | // catch-alls to match on specific patterns. Alternatively, use `Router::with_data(D)` to |
| 27 | // provide arbitrary data that will be accessible in each route via the `ctx.data()` method. |
| 28 | let router = Router::new(); |
| 29 | |
| 30 | // Add as many routes as your Worker needs! Each route will get a `Request` for handling HTTP |
| 31 | // functionality and a `RouteContext` which you can use to and get route parameters and |
| 32 | // Environment bindings like KV Stores, Durable Objects, Secrets, and Variables. |
| 33 | router |
| 34 | .get("/", |_, _| Response::ok("Hello WASM!")) |
| 35 | .get("/worker-version", |_, ctx| { |
| 36 | let version = ctx.var("WORKERS_RS_VERSION")?.to_string(); |
| 37 | Response::ok(version) |
| 38 | }) |
| 39 | .run(req, env) |
| 40 | .await |
| 41 | } |