Skip to content

Instantly share code, notes, and snippets.

@MarkTiedemann
Last active September 6, 2019 22:25
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 MarkTiedemann/7f283d43b34ebc320d6dfee480dc6053 to your computer and use it in GitHub Desktop.
Save MarkTiedemann/7f283d43b34ebc320d6dfee480dc6053 to your computer and use it in GitHub Desktop.
let http = require("http")
let html = String.raw
let cms = {
title: "My Title",
text: "My text"
}
function site(editable) {
let edit = editable ? ` contenteditable="true"` : ""
let save = edit ? html`
<script>
function save() {
let body = JSON.stringify({
title: document.getElementById("title").textContent,
text: document.getElementById("text").textContent
})
fetch("/config", { method: "PUT", body })
}
</script>
<button onclick="save()">Save</button>` : ""
return html`<!DOCTYPE html>${save}
<h1 id="title"${edit}>${cms.title}</h1>
<p id="text"${edit}>${cms.text}</p>
`
}
http.createServer(async function(req, res) {
if (req.url === "/config") {
try {
let buf = []
for await (let chunk of req) buf.push(chunk)
let body = Buffer.concat(buf).toString()
let json = JSON.parse(body)
cms.title = json.title
cms.text = json.text
res.writeHead(200)
res.end()
} catch {
res.writeHead(400)
res.end()
}
} else {
res.writeHead(200, { "content-type": "text/html" })
res.end(site(req.url === "/edit"))
}
}).listen(80)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment