This is part five, the last one, of a series teaching Clojure to people with little or no programming experience.
In Part 4 you built a page that responds to what a visitor types.

In this part we'll create a simple blog.

The plan

To build the blog we need to:

  1. List the files in a posts/ folder.
  2. Convert their format (Markdown) into HTML.
  3. Read one specific file when someone asks for it.

Step 1: Write two posts

Create a folder called posts in the root of your project (next to deps.edn, not inside src).
Inside it create two plain-text files.

posts/hello-world.md:

# Hello, World  This is my first post. ## A subheading  I wrote it in a plain text file. 

posts/second-post.md:

# Second Post  Posts are just files in a folder. 

Markdown is a way of writing formatted text with plain characters: # at the start of a line means "big heading" and ## means "smaller heading". There is more you can do with Markdown, but don't worry about it for now.

Step 2: List the files

Let's explore this in the REPL. If the REPL from Part 4 is still open, you can use it. If not, open a new terminal (Terminal > New Terminal), run clojure, and wait for the user=> prompt.

Before we start, create a third file called posts/notes.txt. It can be empty. It's there to show why we'll need a filter in a minute.

First, tell the REPL which tools we'll use.

(require '[clojure.java.io :as io] '[clojure.string :as str]) ;; nil 

Now let's list the files in the posts folder:

(map #(.getName %) (.listFiles (io/file "posts"))) ;; ("hello-world.md" "second-post.md" "notes.txt") 

Read it from the inside out:

  • (io/file "posts") points to the posts folder.
  • .listFiles asks a folder for what's in it, and .getName asks a file for its name.
  • #(... %) is a function without a name. % is the thing it receives, which here is one file.
  • map runs a function on every item in a list and gives back a new list with the results. Here it turns a list of files into a list of names.

(The names might come in a different order on your computer.)

We only want posts, and notes.txt isn't one.
Use the filter function to filter non-posts out. Also use the str/ends-with? function to keep only the files that end with .md.
Let's wrap filter around what we have:

(filter #(str/ends-with? % ".md") (map #(.getName %) (.listFiles (io/file "posts")))) ;; ("hello-world.md" "second-post.md") 

notes.txt is gone.

It works, but look at how it reads. The first thing that happens (listing the files) is buried in the middle, and the last thing (filter) is at the front.
To understand it you have to start at the innermost line and read your way out.

Clojure has a solution for making this kind of code easier to read: threading macros.
(Think of "threading" as passing a value through a series of steps, like a thread through beads.)
The one we need is called thread last and is written ->>. It takes a value and passes it through the steps, adding the result of each step as the last item of the next one.
Here is the same code, written with it:

(->> (.listFiles (io/file "posts")) (map #(.getName %)) (filter #(str/ends-with? % ".md"))) ;; ("hello-world.md" "second-post.md") 

Same result, much easier to read. Adding more steps is also easier, just add another line at the bottom.

The page we build next will link to each post. If we use the full file name we would get something like /blog/hello-world.md. Let's remove the .md from the names. Try it on one name first:

(str/replace "hello-world.md" #"\.md$" "") ;; "hello-world" 

#"\.md$" is a regular expression (regex for short), a pattern for matching text. This one means ".md, at the very end of the text".
What's left, hello-world, is the slug: the part of the address that identifies a post.

Now add that to the previous function. Let's also sort our list:

(->> (.listFiles (io/file "posts")) (map #(.getName %)) (filter #(str/ends-with? % ".md")) (map #(str/replace % #"\.md$" "")) sort) ;; ("hello-world" "second-post") 

(sort has no parentheses because it needs nothing besides the list. When a step is just a name, ->> reads it as (sort the-previous-result).)

Now that we know it works, let's add it to our website. You can delete posts/notes.txt now. It was only for the experiment.

Update the ns at the top of src/app/core.clj. The only new line is [clojure.java.io :as io]:

(ns app.core (:require [org.httpkit.server :as http] [clojure.java.io :as io] [clojure.string :as str]) (:gen-class)) 

Then add this above handler:

(def posts-dir "posts") (defn list-posts [] (->> (.listFiles (io/file posts-dir)) (map #(.getName %)) (filter #(str/ends-with? % ".md")) (map #(str/replace % #"\.md$" "")) sort)) 

It's what we just tried in the REPL, wrapped in a function so we can call it by name.
def gives a name to a value (here, the folder name), so if we ever rename the folder we only change it in one place.

Save the file, then load it in the REPL and call the function:

(require 'app.core :reload) ;; nil (app.core/list-posts) ;; ("hello-world" "second-post") 

Step 3: Build a page that lists them

This is just another function in the same shape as home-page and about-page. Add it above handler:

(defn blog-list-page [] (page "Blog" (str "<h1>Blog</h1><ul>" (str/join "" (for [slug (list-posts)] (str "<li><a href=\"/blog/" slug "\">" slug "</a></li>"))) "</ul>"))) 

Two things are new:

  • for goes through the slugs and makes one <li> with a link for each of them.
  • str/join glues the items of a list into one piece of text, with whatever you give it first (here "", nothing) between them.

Add a route to handler, before the 404 at the end:

(defn handler [req] (case (:uri req) "/" (html-response 200 (home-page)) "/about" (html-response 200 (about-page)) "/convert" (html-response 200 (convert-page (parse-query (:query-string req)))) "/blog" (html-response 200 (blog-list-page)) (html-response 404 (not-found-page)))) 

And add a link to the new page in the navigation bar. In page, change the <nav> line to:

 "<nav><a href=\"/\">Home</a><a href=\"/about\">About</a><a href=\"/blog\">Blog</a></nav>" 

Save the file, then reload and restart in the REPL: (require 'app.core :reload) (app.core/start-server).
Visit http://localhost:8080/blog, and you should see your two posts listed.
Create a temporary file called posts/test.md (it can be empty), refresh, and it appears in the list. You didn't touch the code, and you didn't even restart: list-posts looks in the folder every time someone visits.
That's the idea of this whole part. Delete test.md again when you're done: we'll add a real third post at the end.

The links go to pages that don't exist yet. Let's fix that.

Step 4: Escape the text

Before we turn Markdown into HTML, we need a helper.
A post is just text, and some characters mean something special to HTML.
If a post says use <h1> for a big heading, the browser reads <h1> as a real tag: it disappears from the sentence, and everything after it turns into one big heading.
Escaping swaps those characters for safe versions: < becomes &lt;, and the browser shows it as <.

We are building this escape function by hand for our educational purposes. In a "real" project you would likely use an existing library to do this.

Add this above handler:

(defn escape-html [s] (-> s (str/replace "&" "&amp;") (str/replace "<" "&lt;") (str/replace ">" "&gt;") (str/replace "\"" "&quot;"))) 
  • -> (aka thread first) is another threading macro, the cousin of ->>. It also passes a value through a series of steps, but it puts the value first, right after the function's name, instead of last.
  • That's where str/replace wants its text, so (str/replace "&" "&amp;") becomes (str/replace s "&" "&amp;").
  • The text goes through four replacements, one after another.
  • The & goes first because the other replacements create & characters of their own, and we don't want to escape those a second time.
  • The last one, "\"", is a double quote escaped with a backslash.

Save the file and try it in the REPL:

(require 'app.core :reload) ;; nil (app.core/escape-html "use <h1> & <p>") ;; "use &lt;h1&gt; &amp; &lt;p&gt;" 

Step 5: Turn Markdown into HTML

Now the converter. It only understands what our posts use: headings, blank lines and paragraphs.
We'll also write a function that finds a post's title.
Add these above handler, below escape-html:

(defn markdown->html [md] (str/join "\n" (for [line (str/split-lines md)] (cond (str/starts-with? line "# ") (str "<h1>" (escape-html (subs line 2)) "</h1>") (str/starts-with? line "## ") (str "<h2>" (escape-html (subs line 3)) "</h2>") (str/blank? line) "" :else (str "<p>" (escape-html line) "</p>"))))) (defn post-title [md] (if-let [heading (first (filter #(str/starts-with? % "# ") (str/split-lines md)))] (subs heading 2) "Untitled")) 

markdown->html goes through the post one line at a time:

  • str/split-lines cuts the text into a list of lines, for goes through them, and str/join glues the results back together with a new line ("\n") between them.
  • cond is like case, but instead of comparing to values it tries each test in order and uses the first one that's true.
  • :else is just a test that is always true, so it works as a default.
  • (subs line 2) means "line without its first 2 characters", which drops the # and keeps the rest. For ## we drop 3.
  • Every piece of text from the post goes through escape-html before it's wrapped in a tag. The tags are ours, and the text in between is the post's.

post-title looks for the line that holds the post's title:

  • filter keeps the lines that start with #, and first takes the first of them, or nil if there are none.
  • if-let is when-let with an "otherwise" branch: if a heading was found, it gets the name heading and the first result is used. If not, the second result, "Untitled", is used.

Save the file and try them in the REPL, with a line that has characters HTML cares about:

(require 'app.core :reload) ;; nil (app.core/markdown->html "# Hi\n\nA <b>test</b> & more") ;; "<h1>Hi</h1>\n\n<p>A &lt;b&gt;test&lt;/b&gt; &amp; more</p>" (app.core/post-title "# Hello, World\n\nSome text") ;; "Hello, World" (app.core/post-title "No heading here") ;; "Untitled" 

Step 6: Read one post

Add these above handler:

(defn read-post [slug] (let [f (io/file posts-dir (str slug ".md"))] (when (.exists f) (slurp f)))) (defn blog-post-page [slug] (when-let [md (read-post slug)] (page (escape-html (post-title md)) (markdown->html md)))) 
  • when runs its body only if the test is true. It's the opposite of when-not. If the file isn't there, read-post gives back nil.
  • slurp reads a whole file into text.
  • The title goes through escape-html too, because page puts it inside the HTML as well.

Save the file and try read-post in the REPL:

(require 'app.core :reload) ;; nil (app.core/markdown->html (app.core/read-post "second-post")) ;; "<h1>Second Post</h1>\n\n<p>Posts are just files in a folder.</p>" (app.core/read-post "nope") ;; nil 

Now the router. /blog is an exact match, but /blog/hello-world has to match on the start of the address, so we can pull the slug out of whatever follows /blog/.
case can't express that, so we'll switch to cond, the more general tool. Replace handler with:

(defn handler [req] (let [uri (:uri req)] (cond (= uri "/") (html-response 200 (home-page)) (= uri "/about") (html-response 200 (about-page)) (= uri "/convert") (html-response 200 (convert-page (parse-query (:query-string req)))) (= uri "/blog") (html-response 200 (blog-list-page)) (str/starts-with? uri "/blog/") (if-let [body (blog-post-page (subs uri (count "/blog/")))] (html-response 200 body) (html-response 404 (not-found-page))) :else (html-response 404 (not-found-page))))) 

There's one small change to make in html-response, right above handler.
Posts can contain accents, curly quotes and other characters that aren't on every keyboard, and the browser has to be told how to read them.
Replace html-response with this version, where the only difference is ; charset=utf-8:

(defn html-response [status body] {:status status :headers {"Content-Type" "text/html; charset=utf-8"} :body body}) 

Save the file, then reload and restart in the REPL: (require 'app.core :reload) (app.core/start-server).
Visit /blog and click through from the list. You have a blog!
Then try an address that isn't a post, like http://localhost:8080/blog/nope. You get your 404 page.

Checkpoint: you have a blog that builds its pages from files.

Before you deploy it, there are two things to fix.

Step 7: Break it

The slug in /blog/hello-world comes straight from a URL someone typed, and we're handing it to the filesystem.
What happens if someone asks for a slug that isn't a post at all?
Remember the README.md you created in Part 2? It's in the project root, outside posts/.

Someone could run a command like:

curl --path-as-is http://localhost:8080/blog/../README 

And get your README back as a web page. That's not good.
The slug was ../README, so the program looked for posts/../README.md. That's a perfectly good path, and .. means "go up one folder".

One possible fix is to validate the slug. Add this above read-post:

(defn valid-slug? [slug] (boolean (re-matches #"[a-zA-Z0-9\-]+" slug))) 

#"[a-zA-Z0-9\-]+" is another pattern. This one means "one or more letters, numbers, or dashes, and nothing else".
re-matches gives back the text if the whole slug fits the pattern and nil if not, and boolean turns that into true or false.
Save the file and try it in the REPL:

(require 'app.core :reload) ;; nil (app.core/valid-slug? "hello-world") ;; true (app.core/valid-slug? "../README") ;; false 

Now make read-post use it. Replace read-post with:

(defn read-post [slug] (when (valid-slug? slug) (let [f (io/file posts-dir (str slug ".md"))] (when (.exists f) (slurp f))))) 

Save the file, then reload and restart in the REPL: (require 'app.core :reload) (app.core/start-server).
Then run the same curl command in the other terminal. Now it gets your 404 page, and your posts still open as before.

Checkpoint: your website now serves posts from files, and it only serves the files you meant it to.

Step 8: Ship the posts

There's one more thing to fix before deploying.

Remember the recipe in Dockerfile.vercel from Part 2? The run stage copies a single file: app.jar.
In Parts 3 and 4 that was enough, because everything new was code inside src, and the code is packed into the jar.
Posts aren't code, so they're not in the jar. Without them, list-posts finds nothing.

So the recipe has to bring the posts folder along. Replace Dockerfile.vercel with:

FROM clojure:temurin-21-tools-deps AS build WORKDIR /app COPY deps.edn build.clj . COPY src src RUN clojure -T:build uber FROM eclipse-temurin:21-jre-alpine WORKDIR /app COPY --from=build /app/target/app.jar app.jar COPY posts posts CMD ["/opt/java/openjdk/bin/java", "-jar", "app.jar"] 

What changed:

  • WORKDIR /app in the run stage makes /app the folder the program runs from.
  • COPY posts posts copies your folder in next to the jar.
  • The jar is now at /app/app.jar instead of /app.jar.

Your project should now look like this:

my-site/ .dockerignore .gitignore Dockerfile.vercel README.md build.clj deps.edn posts/ hello-world.md second-post.md src/ app/ core.clj 

The whole file

Here is the full src/app/core.clj at this point. If something isn't working, compare yours to this one:

(ns app.core (:require [org.httpkit.server :as http] [clojure.java.io :as io] [clojure.string :as str]) (:gen-class)) (defn page [title body] (str "<!DOCTYPE html><html><head><title>" title "</title>" "<style>body{font-family:sans-serif;max-width:600px;margin:40px auto;padding:0 20px}" "nav a{margin-right:12px}</style></head><body>" "<nav><a href=\"/\">Home</a><a href=\"/about\">About</a><a href=\"/blog\">Blog</a></nav>" body "</body></html>")) (defn home-page [] (page "Home" (str "<h1>Hi, I'm Carvalho</h1>" "<p>Welcome to my corner of the internet.</p>" "<ul>" "<li><a href=\"https://github.com\">GitHub</a></li>" "</ul>"))) (defn about-page [] (page "About" (str "<h1>About Me</h1>" "<p>I'm learning Clojure and building my first website!</p>"))) (defn not-found-page [] (page "Not Found" "<h1>404 - Page Not Found</h1>")) (defn url-decode [s] (java.net.URLDecoder/decode s "UTF-8")) (defn parse-query [query-string] (when-not (str/blank? query-string) (into {} (for [pair (str/split query-string #"&") :let [[k v] (str/split pair #"=" 2)]] [(url-decode k) (url-decode (or v ""))])))) (defn celsius->fahrenheit [c] (+ (* c 9/5) 32)) (defn convert-page [params] (let [celsius-str (get params "celsius" "")] (page "Celsius to Fahrenheit" (str "<h1>Celsius to Fahrenheit</h1>" "<form method=\"get\" action=\"/convert\">" "<input type=\"text\" name=\"celsius\" placeholder=\"Enter Celsius\">" "<button type=\"submit\">Convert</button>" "</form>" (when-let [c (parse-double celsius-str)] (str "<p>" c "&deg;C is " (celsius->fahrenheit c) "&deg;F</p>")))))) (def posts-dir "posts") (defn list-posts [] (->> (.listFiles (io/file posts-dir)) (map #(.getName %)) (filter #(str/ends-with? % ".md")) (map #(str/replace % #"\.md$" "")) sort)) (defn blog-list-page [] (page "Blog" (str "<h1>Blog</h1><ul>" (str/join "" (for [slug (list-posts)] (str "<li><a href=\"/blog/" slug "\">" <...
Source:https://dev.to/thiagooak/build-a-blog-in-clojure-16ej