Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a small ruby web server?

Tags:

ruby

webserver

I have a ruby script that also needs to serve a few static files in a directory (such as an index.html, CSS and JS directories). What is the best way to write a little inline web server to serve these files?

Solution:

require 'webrick'
web_server = WEBrick::HTTPServer.new(:Port => 3000, :DocumentRoot => Dir.pwd + '/web')
trap 'INT' { web_server.shutdown }
web_server.start

Or add this to your .bash_profile for an easy way to serve up the files in any directory:

alias serve="ruby -rwebrick -e\"s = WEBrick::HTTPServer.new(:Port => 3000, :DocumentRoot => Dir.pwd); trap('INT') { s.shutdown }; s.start\""
like image 771
Andrew Avatar asked Dec 17 '22 06:12

Andrew


2 Answers

You can use the simplest ruby HTTP server you can find:

ruby -run -e httpd . -p 5000

It will serve content from the running directory on port 5000.

like image 131
Paulo Fidalgo Avatar answered Dec 28 '22 11:12

Paulo Fidalgo


If you're looking for something pure-Ruby and simple, WEBrick is a good choice. Because it is pure-Ruby, it won't go very fast.

Mongrel is partially implemented in C and Ruby and is better for performance than WEBrick. (The Ruby on Rails development mode will use Mongrel in preference to WEBrick if Mongrel is installed.)

If you'd like your server to scale better than either of WEBrick or Mongrel, then thin is probably the choice -- it glues Mongrel together on top of EventMachine to scale further than the other, simpler, systems can scale.

Nothing will quite replace running a full-blown web server such as nginx, but integrating that into your application is significantly more work for you and your users.

like image 26
sarnold Avatar answered Dec 28 '22 10:12

sarnold