philipbohun.com

Glojure by Example: HTTP Server

HandleFunc registers a function on the default mux. The function receives a response writer and a request. Write sends the body. ListenAndServe blocks until the server stops.

(defn hello [w r]
  (let [path (.Path (.URL r))]
    (.Write w (str "hello " path))
    nil))

(net:http.HandleFunc "/hello/" hello)
(println "listening on 127.0.0.1:18081")
(let [err (net:http.ListenAndServe "127.0.0.1:18081" nil)]
  (when err
    (println (.Error err))))

The process prints the address and then serves. Stop it with Ctrl-C.

$ glj http-server.glj
listening on 127.0.0.1:18081

From another shell, request a path under /hello/.

$ curl -s http://127.0.0.1:18081/hello/world
hello /hello/world

Next example: Context.