You want to create a HTTP server over a network. Over the course of this recipe, we’ll go step by step from the smallest server possible to a functional key-value store.
Solution
We’ll use node.js’s HTTP library to our own selfish purposes and create the simplest web server possible in Coffeescript.
Say ‘hi\n’
We can start by importing node.js’s HTTP module. This contains createServer which, given a simple request handler, returns a HTTP server. We can use that server to listen on a TCP port.
To run this example, simply put in a file and run it. You can kill it with Ctrl-C. We can test it using the curl command, available on most *nix platforms:
What’s going on?
Let’s get a little bit more feedback on what’s happening on our server. While we’re at it, we could also be friendlier to our clients and provide them some HTTP headers.
Try to access it once again, but this time use different URL paths, such as http://localhost:8000/coffee. You’ll see something like this on the server console:
GETting stuff
What if our webserver was able to hold some data? We’ll try to come up with a simple key-value store in which elements are retrievable via GET requests. Provide a key on the request path and the server will return the corresponding value — or 404 if it doesn’t exist.
We can try several URLs to see how it responds:
Use your head(ers)
Let’s face it, text/plain is kind of lame. How about if we use something hip like application/json or text/xml? Also, our store retrieval process could use a bit of refactoring — how about some exception throwing & handling? Let’s see what we can come up with:
This server will still return the value which matches a given key, or 404 if non-existent. But it will structure the response either in JSON or XML, according to the Accept header. See for yourself:
You gotta give to get back
The obvious last step in our adventure is to provide the client the ability to store data. We’ll keep our RESTiness by listening to POST requests for this purpose.
Notice how the data is received in a POST request. By attaching some handlers on the 'data' and 'end' events of the request object, we’re able to buffer and finally save the data from the client in the store.
Discussion
Give http.createServer a function in the shape of (request, response) -> ... and it will return a server object, which we can use to listen on a port. Interact with the request and response objects to give the server its behaviour. Listen on port 8000 using server.listen 8000.
For API and overall information on this subject, check node.js’s http and https documentation pages. Also, the HTTP spec might come in handy.
Exercises
Create a layer in between the server and the developer which would allow the developer to do something like: