Clojure is a modern Lisp that runs on the Java Virtual Machine (JVM). It is a functional programming language that emphasizes simplicity and immutability, making it an excellent choice for beginners. Here are a few reasons why Clojure is a great starting point:

  1. Simplicity: Clojure has a simple syntax that allows beginners to focus on learning programming concepts rather than getting bogged down by complex syntax rules.
  2. Interactive Development: Clojure’s REPL (Read-Eval-Print Loop) allows for interactive programming, making it easy to test and experiment with code in real-time.
  3. Immutable Data Structures: Clojure encourages the use of immutable data structures, which can help beginners understand the importance of state management in programming.
  4. Rich Ecosystem: With access to Java libraries and a growing community, beginners can leverage a wealth of resources and tools.

Checking URLs with Babashka and Curl

In this post, we will demonstrate how to check different URLs using Babashka and Curl. Babashka is a scripting environment for Clojure that allows you to run Clojure scripts quickly and easily.

Prerequisites

  • Install Babashka: Follow the instructions on the Babashka website.
  • Ensure Curl is installed on your system.

Sample Code

Here’s a simple script that checks the status of multiple URLs and logs the output:

#!/usr/bin/env bb

(require '[babashka.curl :as curl])
(import '[java.time LocalDateTime]
        '[java.time.format DateTimeFormatter])

(def urls ["https://www.google.com" "https://www.example.com" "https://nonexistent.url"])

(defn current-timestamp []
  (let [formatter (DateTimeFormatter/ofPattern "yyyy-MM-dd HH:mm:ss")]
    (.format (LocalDateTime/now) formatter)))

(defn check-url [url]
  (let [response (curl/get url {:throw false})
        timestamp (current-timestamp)]
    (if (= 200 (:status response))
      (println (str "[" timestamp "] URL: " url " - Status: OK (" (:status response) ")"))
      (println (str "[" timestamp "] URL: " url " - Status: " (:status response) " - Error: " (:body response))))))

(doseq [url urls]
  (check-url url))

Explanation of the Code

This code leverages babashka’s curl library, along with Java’s java.time library, to make HTTP requests and log the status with a timestamp. Here’s how it works:

  1. Timestamp Generation:

    • The current-timestamp function uses LocalDateTime and DateTimeFormatter to get the current date and time in YYYY-MM-DD HH:MM:SS format. This is a practical approach for logging, especially in production or monitoring scripts.
  2. Checking URLs:

    • The check-url function takes each URL, performs an HTTP GET request using curl/get, and captures the response status and body. With the addition of { :throw false }, the function gracefully handles errors without throwing exceptions, allowing us to provide detailed feedback on each request.
    • If the response status is 200, it logs a success message; otherwise, it logs an error with the response body.
  3. Logging Each Check:

    • By combining both the URL status and timestamp, each result is logged in a readable format that can easily be adapted for more advanced logging needs.

Inspiration for the Curious Developer

“One must still have chaos in oneself to be able to give birth to a dancing star.”
Thus Spoke Zarathustra, Friedrich Nietzsche

This code is a simple, modular approach to HTTP monitoring, reflecting Nietzsche’s wisdom on the creative potential within chaos. Each function here is pure and straightforward, yet it can be combined and adapted to handle complex tasks with ease. The beauty of functional programming is in the simplicity of each function, yet by evaluating and composing these small functions, you can create powerful tools. With minimal changes, you can unlock more advanced features, encouraging growth and experimentation.

Remember: in every piece of simple code lies the potential for elegance and power.


Ideas for Extending This Code

This script can be a starting point for more robust utilities. Here are a couple of examples to get you started:

  1. Save Logs to a File: Modify the code to write log entries to a file instead of printing to the console. This could be useful for monitoring tools or scheduled cron jobs.
  2. Alert on Specific Status Codes: Extend the check-url function to send an alert (like an email or a Slack message) when certain HTTP status codes are encountered, such as 404 or 500.

Feel free to adapt these ideas and explore new directions with this code! Each small change opens up exciting possibilities for managing and automating tasks, and as you experiment, you might find even more applications and insights along the way.