javaclojurejavalin

How to translate a simple web framework in Javalin into Clojure?


There is a simple web framework in Javalin

import io.javalin.Javalin;

public class HelloWorld {
    public static void main(String[] args) {
        var app = Javalin.create(/*config*/)
            .get("/", ctx -> ctx.result("Hello World"))
            .start(7070);
    }
}

Translated into Clojure.

(ns javalin.javalin101)

(import 'io.javalin.Javalin)

(defn -main []
  (let [app (Javalin/create)]
    (Javalin/get app "/" (fn [ctx] (.result ctx "Hello World")))
    (.start app 7070)))

deps.edn

{:paths ["src"]
 :deps
 {org.clojure/clojure {:mvn/version "1.11.1"}
  org.clojure/core.async {:mvn/version "1.6.673"}
  org.clojure/data.json {:mvn/version "2.4.0"}
  clj-time/clj-time {:mvn/version "0.15.2"}
  ;; java 
  io.javalin/javalin {:mvn/version "5.5.0"}}}

When I execute with calve-repl, an error encounter

; Syntax error (IllegalArgumentException) compiling . at (src/javalin/javalin101.clj:7:5).
; No matching method get found taking 3 args for class io.javalin.Javalin

Please feel free to comment how to fix it.


Solution

  • The first issue with your code, is that you are making a call to a non-existent static method of the Javalin class. Your call to get approximately translates to:

    Javalin.get(app, "/", (ctx) -> ctx.result("Hello World"));
    

    Just as you call result on ctx with (.result ctx "Hello World"), you need to call get the same way: (.get app "/" (fn ...)).

    However, you will see that you are not getting the appropriate type for the handler function. Use reify to create an instance of Handler - you just have to add another argument to handle ("this"):

    Dependency: [io.javalin/javalin "5.5.0"]
    
    (ns ...
      (:import (io.javalin Javalin)
               (io.javalin.http Handler))
      (:gen-class))
    
    (defn -main []
      (doto (Javalin/create)
        (.get "/" (reify Handler
                    (handle [_ ctx] (.result ctx "Hello World"))))
        (.start 7070)))
    

    You can also use proxy:

    (defn -main []
      (doto (Javalin/create)
        (.get "/" (proxy [Handler] []
                    (handle [ctx] (.result ctx "Hello World"))))
        (.start 7070)))