--- layout: doc title: HTTP server ---
The server uses an event-driven, non-blocking I/O model that makes it lightweight and scalable. It's written to conform to the standard Clojure web server Ring spec, with asynchronous and websocket extension. HTTP Kit is (almost) drop-in replacement of ring-jetty-adapter
run-server
starts a Ring-compatible HTTP server. You may want to do routing with compojure
:ip
: which IP to bind, default to 0.0.0.0
:port
: which port listens for incoming requests, default to 8090:thread
: How many threads to compute response from request, default to 4:worker-name-prefix
: worker thread name prefix, default to worker-
: worker-1
worker-2
....:queue-size
: max requests queued waiting for thread pool to compute response before rejecting, 503(Service Unavailable) is returned to client if queue is full, default to 20K:max-body
: length limit for request body in bytes, 413(Request Entity Too Large) is returned if request exceeds this limit, default to 8388608(8M):max-line
: length limit for HTTP initial line and per header,
414(Request-URI Too Long) will be returned if exceeding this limit, default to 8192(8K),
relevant discussion on Stack Overflow
run-server
returns a function that stops the server, which can take an optional timeout(ms) param to wait for existing requests to be finished.
The with-channel API is not compatible with the RC releases. The new one is better and much easier to understand and use. The old documentation is here
Unified asynchronous channel interface for HTTP (streaming or long-polling) and WebSocket.
Channel defines the following contract:open?
: Returns true iff channel is open.
close
: Closes the channel. Idempotent: returns true if the channel was actually closed, or false if it was already closed.
websocket?
: Returns true iff channel is a WebSocket.
send!
:
Sends data to client and returns true if the data was successfully written to the output queue, or false if the
channel is closed. Normally, checking the returned value is not needed. This function returns immediately (does not
block).
Data is sent directly to the client, NO RING MIDDLEWARE IS APPLIED.
Data form: {:headers _ :status _ :body _} or just body. Note that :headers and :status will be stripped for WebSockets and for HTTP streaming responses after the first.
on-receive
:
Sets handler (fn [message-string || byte[]) for notification of client WebSocket
messages. Message ordering is guaranteed by server.
on-close
:
Sets handler (fn [status]) for notification of channel being closed by the
server or client. Handler will be invoked at most once. Useful for clean-up. Status can be `:normal`, `:going-away`, `:protocol-error`, `:unsupported`, `:unknown`, `:server-close`, `:client-close`
send!
,
sends HTTP status and Headers to clientsend!
sends a chunk to clientclose
sends an empty chunk to client, marking the end of the responseon-close
Long polling is very much like streaming
chat-polling is a realtime chat example of using polling
{% highlight clojure %} (def channel-hub (atom {})) (defn handler [request] (with-channel request channel ;; Store the channel somewhere, and use it to send response to client when interesting event happens (swap! channel-hub assoc channel request) (on-close channel (fn [status] ;; remove from hub when channel get closed (swap! channel-hub dissoc channel))))) (on-some-event ;; send data to client (doseq [channel (keys @channel-hub)] (send! channel {:status 200 :headers {"Content-Type" "application/json; charset=utf-8"} :body data}))) (run-server handler {:port 9090}) {% endhighlight %}send!
with java.lang.String
, a text frame assembled and sent to client
send!
with java.io.InputStream
or byte[]
, a binary frame assembled and sent to client
The with-channel
does the WebSocket handshake automatically. In case if you want to control it, e.g., to support WebSocket subprotocol,
here is a workaround. cgmartin's gist is a good place to get inspired.
Compojure can be used to do the routing, based on uri and method
{% highlight clojure %} (:use [compojure.route :only [files not-found]] [compojure.core :only [defroutes GET POST DELETE ANY context]] org.httpkit.server) (defn show-landing-page [req] ;; ordinary clojure function, accepts a request map, returns a response map ;; return landing page's html string. Using template library is a good idea: ;; mustache (https://github.com/shenfeng/mustache.clj, https://github.com/fhd/clostache...) ;; enlive (https://github.com/cgrand/enlive) ;; hiccup(https://github.com/weavejester/hiccup) ) (defn update-userinfo [req] ;; ordinary clojure function (let [user-id (-> req :params :id) ; param from uri password (-> req :params :password)] ; form param .... )) (defroutes all-routes (GET "/" [] show-landing-page) (GET "/ws" [] chat-handler) ;; websocket (GET "/async" [] async-handler) ;; asynchronous(long polling) (context "/user/:id" [] (GET / [] get-user-by-id) (POST / [] update-userinfo)) (files "/static/") ;; static file url prefix /static, in `public` folder (not-found "Page not found.
")) ;; all other, return 404 (run-server all-routes {:port 8080}) {% endhighlight %}http-kit runs alone happily, handy for development and quick deployment. Use of a reverse proxy like Nginx, Lighthttpd, etc in serious production is encouraged. They can also be used to add https support.
Sample Nginx configration:
{% highlight sh %} upstream http_backend { server 127.0.0.1:8090; # http-kit listen on 8090 # put more servers here for load balancing # keepalive(resue TCP connection) improves performance keepalive 32; # both http-kit and nginx are good at concurrency } server { location /static/ { # static content alias /var/www/xxxx/public/; } location / { proxy_pass http://http_backend; # tell http-kit to keep the connection proxy_http_version 1.1; proxy_set_header Connection ""; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; access_log /var/log/nginx/xxxx.access.log; } } {% endhighlight %}