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.
(ns webserver.core
(:use server.socket
[clojure.string :as str :only [split]]))
(import '(java.io PrintWriter BufferedReader InputStreamReader))
(def port 5000)
(defn webserver [in out]
(binding
[ *out* (PrintWriter. out)]
(println "HTTP/1.0 200 OK")
(println "Content-Type: text/html")
(println "")
(println "<h1>You are connected to my web server!</h1>")))
(defn -main []
(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!