Skip to content

Instantly share code, notes, and snippets.

@borkdude
Last active December 30, 2021 18:56
Show Gist options
  • Save borkdude/843548cba14ae9d283191e31bc483959 to your computer and use it in GitHub Desktop.
Save borkdude/843548cba14ae9d283191e31bc483959 to your computer and use it in GitHub Desktop.
(ns guestbook
(:require [cheshire.core :as cheshire]
[hiccup2.core :as hiccup]
[clojure.string :as str]))
(require '[babashka.pods :as pods])
(pods/load-pod "./pod-babashka-postgresql")
(def db {:dbtype "postgresql"
:user "guestbook"
:password "guestbook"
:database "guestbook"
:port 5434})
(require '[pod.babashka.postgresql :as sql])
(def post-data (-> (System/getenv "POST_DATA")
(cheshire/parse-string
true)))
(let [{:keys [name message]} post-data]
(when (and name (not (str/blank? name))
message (not (str/blank? message)))
(try (sql/execute! db ["insert into guestbook (name, message, _created) values (?,?, now())"
name message])
(catch Exception e
(prn e)))))
(def entries (sql/execute! db ["select * from guestbook order by _created desc limit 10"]))
(defn render-messages []
[:table.table
[:thead
[:tr
[:th "Name"]
[:th "Greeting"]]]
[:tbody
(for [{:guestbook/keys [name message]} entries]
[:tr
[:td name]
[:td message]])]])
(defn render-query-params []
(hiccup/html {:escape-strings? false}
(cheshire/parse-string (System/getenv "QUERY_PARAMS")
true)))
(defn render-form []
[:div.mb-3
[:form {:method "POST"}
[:label.form-label {:for "name"} "Name:"]
[:input.form-control {:type "text"
:name "name"
:id "name"}]
[:label.form-label {:for "message"} "Message:"]
[:input.form-control {:type "text"
:name "message"
:id "message"}]
[:input.btn.btn-primary
{:type "submit"
:value "Submit"}]]])
(println
(str "<!doctype html>"
(hiccup/html
[:html {:lang "en"}
[:head
[:link {:rel "stylesheet"
:href "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
:integrity "sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
:crossorigin "anonymous"}]]
[:body.container
[:div "Welcome to my guestbook!"]
[:div (render-form)]
[:div "Last 10 entries:"
(render-messages)]]])))
<?php
$post_data=escapeshellarg(json_encode($_POST));
$query_params=escapeshellarg(json_encode($_GET));
passthru("POST_DATA=$post_data QUERY_PARAMS=$query_params ./bb guestbook.clj");
?>
@borkdude
Copy link
Author

borkdude commented Dec 29, 2021

Screen Shot 2021-12-29 at 22 34 35

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment