The Simpelest Mongrel Server (Without Rails)

I tried to make my own small server and mongrel came in handy!
Some things i covered:

  • making the server stop on ctr+c
  • ignoring favicon requests
  • using the local ip (192.168.X.X) or localhost
  • parsing the request parameters (?aaa=bbb&…) to a hash

The rest is up to you!

Stick your code into process, then run ‘ruby server.rb’ and your done 🙂

#server.rb
require 'mongrel'
require 'yaml'

module SimpleServer
  class SimpleHandler < Mongrel::HttpHandler
    def process(request, response)
      return if request.params['REQUEST_URI']=='/favicon.ico'

      params = extract_params request
      puts "Called with:"
      puts params.to_yaml

      response.start(200) do |head,out|
        head["Content-Type"] = "text/plain"
        out.write("HELLO WORLD!")
      end
    end

    def extract_params request
      params = request.params['QUERY_STRING']
      return {} if !params

      arr = params.split('&')

      hash = {}
      arr.each do |value|
        break if !value
        temp = value.split('=')
        hash[temp[0]]= temp[1]
      end 

      hash
    end
  end

  #SERVER
  def self.start
    require 'socket'
    #or use 'localhost' if u do not want to be callable from outside
    host = IPSocket.getaddress(Socket.gethostname)
    config = Mongrel::Configurator.new :host => host, :port => 3000 do
      listener {uri "/", :handler => SimpleHandler.new}
      trap("INT") { stop }
      run
    end

    #show what we are running
    puts "Running at"
    puts config.defaults.to_yaml
    config.join
  end
end

SimpleServer::start
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s