Tuesday, 17 June 2014

A Dummy REST API with Go Lang

Sometimes I just want to try out a few ideas in a HTML/JavaScript client without having to scaffold a server to provide a bunch of RESTful APIs so I've built myself a dummy REST API to do just that.

Here's how I did it!

My requirements were:
  • Serve up the contents of a file based on a route for example \Customers would serve a file in the \Customers directory
  • Allow Cross-origin resource sharing and/or JSONP 
  • Allow me to change the JSON being served without having to restart anything

I decided to write the server in Go Lang since it's fun to scaffold up http web services with and the resultant utility will be cross platform so I can tinker away on my Mac with few issues. I've used Martini framework to get up and running quickly.

So the file directory will contain the files that I want to serve up as per:

The code to scan the file directory for the files is straightforward:

The code to serve up the file based on the matching route:

So with the GET file populated with some appropriate JSON:

So now when we run the servicestub application:

And if we choose a specific item:

Now to write some JavaScript!

Code here: