Skip to content

Fix various Rust documentation formatting issues #23650

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: production
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 20 additions & 19 deletions src/content/docs/workers/examples/basic-auth.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -260,21 +260,22 @@ export default {
```

</TabItem> <TabItem label="Rust" icon="seti:rust">

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI this blank space is what prevents (I think) prettier from treating the code block as markdown code which is what leads to it mangling the code.

```rs
use base64::prelude::*;
use worker::*;

#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {
let basic_user = "admin";
// You will need an admin password. This should be
// attached to your Worker as an encrypted secret.
// Refer to https://developers.cloudflare.com/workers/configuration/secrets/
let basic_pass = match env.secret("PASSWORD") {
Ok(s) => s.to_string(),
Err(_) => "password".to_string(),
};
let url = req.url()?;
let basic_user = "admin";
// You will need an admin password. This should be
// attached to your Worker as an encrypted secret.
// Refer to https://developers.cloudflare.com/workers/configuration/secrets/
let basic_pass = match env.secret("PASSWORD") {
Ok(s) => s.to_string(),
Err(_) => "password".to_string(),
};
let url = req.url()?;

match url.path() {
"/" => Response::ok("Anyone can access the homepage."),
Expand Down Expand Up @@ -328,10 +329,10 @@ let url = req.url()?;
}
_ => Response::error("Not Found.", 404),
}

}

````
```

</TabItem> <TabItem label="Hono" icon="seti:typescript">

```ts
Expand All @@ -346,17 +347,17 @@ import { basicAuth } from "hono/basic-auth";

// Define environment interface
interface Env {
Bindings: {
Bindings: {
USERNAME: string;
PASSWORD: string;
};
PASSWORD: string;
};
}

const app = new Hono<Env>();

// Public homepage - accessible to everyone
app.get("/", (c) => {
return c.text("Anyone can access the homepage.");
return c.text("Anyone can access the homepage.");
});

// Admin route - protected with Basic Auth
Expand All @@ -365,19 +366,19 @@ app.get(
async (c, next) => {
const auth = basicAuth({
username: c.env.USERNAME,
password: c.env.PASSWORD
})
password: c.env.PASSWORD,
});

return await auth(c, next);
},
(c) => {
return c.text("🎉 You have private access!", 200, {
"Cache-Control": "no-store",
});
}
},
);

export default app;
````
```

</TabItem> </Tabs>
107 changes: 54 additions & 53 deletions src/content/docs/workers/examples/cors-header-proxy.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -583,67 +583,69 @@ async def on_fetch(request):
```

</TabItem> <TabItem label="Rust" icon="seti:rust">

```rs
use std::{borrow::Cow, collections::HashMap};
use worker::*;

fn raw*html_response(html: &str) -> Result<Response> {
Response::from_html(html)
fn raw_html_response(html: &str) -> Result<Response> {
Response::from_html(html)
}
async fn handle_request(req: Request, api_url: &str) -> Result<Response> {
let url = req.url().unwrap();
let mut api_url2 = url
.query_pairs()
.find(|x| x.0 == Cow::Borrowed("apiurl"))
.unwrap()
.1
.to_string();
if api_url2 == String::from("") {
api_url2 = api_url.to_string();
}
let mut request = req.clone_mut()?;
\*request.path_mut()? = api_url2.clone();
if let url::Origin::Tuple(origin, *, _) = Url::parse(&api_url2)?.origin() {
(\*request.headers_mut()?).set("Origin", &origin)?;
}
let mut response = Fetch::Request(request).send().await?.cloned()?;
let headers = response.headers_mut();
if let url::Origin::Tuple(origin, _, \_) = url.origin() {
headers.set("Access-Control-Allow-Origin", &origin)?;
headers.set("Vary", "Origin")?;
}
let url = req.url().unwrap();
let mut api_url2 = url
.query_pairs()
.find(|x| x.0 == Cow::Borrowed("apiurl"))
.unwrap()
.1
.to_string();
if api_url2 == String::from("") {
api_url2 = api_url.to_string();
}
let mut request = req.clone_mut()?;
*request.path_mut()? = api_url2.clone();
if let url::Origin::Tuple(origin, _, _) = Url::parse(&api_url2)?.origin() {
(*request.headers_mut()?).set("Origin", &origin)?;
}
let mut response = Fetch::Request(request).send().await?.cloned()?;
let headers = response.headers_mut();
if let url::Origin::Tuple(origin, _, _) = url.origin() {
headers.set("Access-Control-Allow-Origin", &origin)?;
headers.set("Vary", "Origin")?;
}

Ok(response)

}

fn handle*options(req: Request, cors_headers: &HashMap<&str, &str>) -> Result<Response> {
let headers: Vec<*> = req.headers().keys().collect();
if [
"access-control-request-method",
"access-control-request-headers",
"origin",
]
.iter()
.all(|i| headers.contains(&i.to_string()))
{
let mut headers = Headers::new();
for (k, v) in cors_headers.iter() {
headers.set(k, v)?;
}
return Ok(Response::empty()?.with_headers(headers));
fn handle_options(req: Request, cors_headers: &HashMap<&str, &str>) -> Result<Response> {
let headers: Vec<_> = req.headers().keys().collect();
if [
"access-control-request-method",
"access-control-request-headers",
"origin",
]
.iter()
.all(|i| headers.contains(&i.to_string()))
{
let mut headers = Headers::new();
for (k, v) in cors_headers.iter() {
headers.set(k, v)?;
}
return Ok(Response::empty()?.with_headers(headers));
}
Response::empty()
}
Response::empty()
} #[event(fetch)]
async fn fetch(req: Request, \_env: Env, \_ctx: Context) -> Result<Response> {
let cors_headers = HashMap::from([
("Access-Control-Allow-Origin", "*"),
("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS"),
("Access-Control-Max-Age", "86400"),
]);
let api_url = "https://examples.cloudflareworkers.com/demos/demoapi";
let proxy_endpoint = "/corsproxy/";
let demo_page = format!(

#[event(fetch)]
async fn fetch(req: Request, _env: Env, _ctx: Context) -> Result<Response> {
let cors_headers = HashMap::from([
("Access-Control-Allow-Origin", "*"),
("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS"),
("Access-Control-Max-Age", "86400"),
]);
let api_url = "https://examples.cloudflareworkers.com/demos/demoapi";
let proxy_endpoint = "/corsproxy/";
let demo_page = format!(
r#"

<!DOCTYPE html>
Expand Down Expand Up @@ -696,7 +698,7 @@ return response.json()
</body>
</html>
"#
);
);

if req.url()?.path().starts_with(proxy_endpoint) {
match req.method() {
Expand All @@ -708,7 +710,6 @@ return response.json()
raw_html_response(&demo_page)

}

```
</TabItem> </Tabs>
```

11 changes: 6 additions & 5 deletions src/content/docs/workers/examples/logging-headers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -59,16 +59,17 @@ async def on_fetch(request):
```

</TabItem> <TabItem label="Rust" icon="seti:rust">

```rs
use worker::*;

#[event(fetch)]
async fn fetch(req: HttpRequest, \_env: Env, \_ctx: Context) -> Result<Response> {
console_log!("{:?}", req.headers());
Response::ok("hello world")
async fn fetch(req: HttpRequest, _env: Env, _ctx: Context) -> Result<Response> {
console_log!("{:?}", req.headers());
Response::ok("hello world")
}
```

````
</TabItem> <TabItem label="Hono" icon="seti:typescript">

```ts
Expand Down Expand Up @@ -98,7 +99,7 @@ app.get('*', (c) => {
});

export default app;
````
```

</TabItem> </Tabs>

Expand Down
4 changes: 3 additions & 1 deletion src/content/docs/workers/examples/security-headers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ async def on_fetch(request):
```

</TabItem> <TabItem label="Rust" icon="seti:rust">

```rs
use std::collections::HashMap;
use worker::*;
Expand Down Expand Up @@ -329,7 +330,8 @@ async fn fetch(req: Request, _env: Env, _ctx: Context) -> Result<Response> {

}

````
```

</TabItem> <TabItem label="Hono" icon="seti:typescript">

```ts
Expand Down
Loading