# if this file has a .txt extension, change it to .rb
# this is a ruby script to start a very simple web service.
# it requires the Sinatra gem (run: gem install sinatra)
# then you can run it with: ruby service.rb
# The service will be at http://localhost:4567/ 

require 'sinatra'

def get_content_type(file_name)
  return 'text/javascript' if File.extname(file_name) == '.js'
  return 'text/html' if File.extname(file_name) == '.html'
  return 'text/css' if File.extname(file_name) == '.css'
  'text/plain'
end

get '/' do
  s =  '<title>Examples</title>'
  s <<  '<h1>Examples</h1>'
  s << '<ul>'
  Dir.glob('*.html') do |f|
    s << "<li><a href=file/#{f}>#{File.basename(f,'.*')}</a></li>"
  end
  s << '</ul>'
end

# url: /getdata?d=delay_miliseconds&m=return_value
# both parameters are optional
get '/getdata' do
  delay_ms = (params[:d]||0).to_i
  sleep delay_ms/1000.0
  params[:m] || '(pretend this is real data)'
end

# url: /file/my_static_file.html
# this just returns the file "my_static_file.html"
get '/file/:name' do |name|
  content_type get_content_type(name), :charset => 'utf-8'
  File.read(name)
end