Skip to content

Instantly share code, notes, and snippets.

@badboy
Last active December 28, 2023 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save badboy/13dae661300e7e09b6f5430297fc341c to your computer and use it in GitHub Desktop.
Save badboy/13dae661300e7e09b6f5430297fc341c to your computer and use it in GitHub Desktop.
#!/usr/bin/env -S cargo +nightly -q -Zscript
```cargo
[dependencies]
cgi2 = "0.7"
rusqlite = { version = "0.30.0", features = ["bundled"] }
axohtml = { git = "https://github.com/badboy/axohtml", branch = "nightly-fixes" }
```
use axohtml::{dom::DOMTree, html, text, types::Metadata};
use rusqlite::Connection;
#[cgi::main]
fn main(_request: cgi::Request) -> cgi::Response {
let conn = Connection::open("/tmp/cgi-counter.db").expect("cannot open db");
conn.execute(
"CREATE TABLE IF NOT EXISTS counter (
visits INTEGER
)",
(),
)
.unwrap();
conn.execute(
"INSERT INTO counter(visits) SELECT 0 WHERE NOT EXISTS (SELECT * FROM counter)",
(),
)
.unwrap();
let counter = conn
.query_row(
"UPDATE counter SET visits = visits + 1 RETURNING visits",
[],
|row| row.get(0),
)
.unwrap_or(0);
let doc: DOMTree<String> = html!(
<html>
<head>
<title>"Hello from Rust"</title>
<meta name=Metadata::Author content="cargo"/>
</head>
<body>
<h1>"Hello from Rust"</h1>
<p class="official">
"Rust can do CGI."
</p>
<p>
{ text!("This site has been loaded {} times.", counter) }
</p>
</body>
</html>
);
let doc_str = doc.to_string();
cgi::html_response(200, &doc_str)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment