« back

A Very Agreeable Web Server in Clojure

10 Dec 2012

Blog in 15 minutes? How about an agreeable web server in 5?

Today I was given the task to build a web server. After being primed with my echo server and my command parser projects, (good call Doug) I feel ready for the challenge. After all of the work involved with getting those two tasks under my belt I have less of a "...Web server's. How do they work?" attitude and more of a "Hey, let's pop the hood open and take a look inside." attitude. I have also been liking clojure a lot.(minus some documentation issues) Alright, let's get to it.

So the task itself was to create a web server that would give a 200 OK response. Most of the day was spent reading about requests and responses, streams and writers, and trying to figure out just what the heck I needed to do exactly. Well, because I'm resourceful and I try to be DRY when I can be, I decided to visit my echo server for some cues.

I knew I would need server.socket again and some kind of writer. Once armed with the knowledge about what needs to go into a response- An initial response line, maybe some headers, a blank line, and some content, I was ready to rock.

 1 (ns webserver.core
 2 	(:use server.socket
 3 		[clojure.string :as str :only [split]]))
 4 	(import '(java.io PrintWriter BufferedReader InputStreamReader))
 5 
 6 (def port 5000)
 7 
 8 (defn webserver [in out]
 9 	(binding
10 	      [ *out* (PrintWriter. out)]
11 	      (println "HTTP/1.0 200 OK")
12 	      (println "Content-Type: text/html")
13 	      (println "")
14 		  (println "<h1>You are connected to my web server!</h1>")))
15 
16 (defn -main []
17 (create-server port webserver))

Now you just need to run your server, go to localhost 5000, and BAM!!!!!! You have a web server up and running. This only responds with 200 OK and says 'You are connected to my web server!' no matter what the request,(which is why I say it is agreeable) but we are up and running!

Woo Hoo!

comments powered by Disqus