Skip to content

Instantly share code, notes, and snippets.

@idozorenko
Created December 7, 2020 11:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idozorenko/2710c607e40acecbcb569b66a34813b2 to your computer and use it in GitHub Desktop.
Save idozorenko/2710c607e40acecbcb569b66a34813b2 to your computer and use it in GitHub Desktop.
Simple REST service in Clojure
(ns example.core
(:require [org.httpkit.server :as http-kit]
[compojure.api.sweet :refer :all]
[ring.util.http-response :refer :all]))
(def counter (atom 0)) ;; declare counter
(defn greeting-handler [req] ;; ordinary clojure function, accepts request map, returns a response map
(let [name (-> req :params :name (or "world"))] ;; get param from url or use "world" by default
(ok ;; wraps data with status code 200
{:id (swap! counter inc) ;; increment counter
:name (str "Hello, " name "!")})))
(def app
(api ;; wrap routes with useful middleware provided by compojure-api
(GET "/greeting" [] greeting-handler)))
(defonce server ;; declare server variable once
(http-kit/run-server #'app {:port 8080})) ;; #'app allows to hot swap changes in handlers
@idozorenko
Copy link
Author

Same service as in Spring docs example, but written in Clojure using Compojure API (routing and middleware) and http-kit server

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