Thursday, March 10, 2016

Ruby's One-liner HTTP Server

For years I relied on Python's SimpleHTTPServer module when I wanted to stand up an ad-hoc web service for file transfers. For example, using Python 2.x:
python -m SimpleHTTPServer 8080

Or with Python 3.x:
python -m http.server 8000

Now while this is in fact easy to remember and works quite well, it is one of the only times I ever use Python over my chosen language of Ruby. That was until I discovered the most excellently named lib 'un'. It has been included in main since Ruby 1.9.2 and allows us to stand up a web server in no time at all. For example:
ruby -run -e httpd . -p 8080

 A quick breakdown of what's happening here:
  • -r is the shorthand for a require statement in ruby. Since the library we are loading is called 'un', it reads as 'run', a fantastically clever name indeed. Obviously, you could also invoke it as '-r un' but that's nowhere near as clever.
  • -e invokes the 'httpd' method as defined in the un.rb library. 
  • . is indicated to host the current working directory as the DocumentRoot,
  • -p 8080 is setting the Port option. 
Take a look in the un.rb source and you'll see it is just standing up a WEBrick server in the background. 

Example of running this on my Mac:


No comments:

Post a Comment