|
Revision 34, 1.5 kB
(checked in by why, 3 years ago)
|
|
camping.gemspec: version 1.2.
lib/camping.rb: trying to reflow.
examples/serve: chdir into each example directory when running its app.
|
-
Property svn:executable set to
*
|
| Line | |
|---|
| 1 | #!/usr/bin/env ruby |
|---|
| 2 | # |
|---|
| 3 | # Serves all examples, mounted into Webrick. |
|---|
| 4 | # |
|---|
| 5 | require 'stringio' |
|---|
| 6 | require 'webrick/httpserver' |
|---|
| 7 | |
|---|
| 8 | dir = Dir.pwd |
|---|
| 9 | apps = |
|---|
| 10 | Dir['*'].select do |d| |
|---|
| 11 | Dir.chdir(dir) |
|---|
| 12 | if File.exists? "#{d}/#{d}.rb" |
|---|
| 13 | begin |
|---|
| 14 | Dir.chdir("#{dir}/#{d}") |
|---|
| 15 | load "#{d}.rb" |
|---|
| 16 | true |
|---|
| 17 | rescue Exception => e |
|---|
| 18 | puts "Camping app `#{d}' will not load: #{e.class} #{e.message}" |
|---|
| 19 | end |
|---|
| 20 | end |
|---|
| 21 | end |
|---|
| 22 | apps.map! do |app| |
|---|
| 23 | [app, (Object.const_get(Object.constants.grep(/^#{app}$/i)[0]) rescue nil)] |
|---|
| 24 | end |
|---|
| 25 | |
|---|
| 26 | s = WEBrick::HTTPServer.new(:BindAddress => '0.0.0.0', :Port => 3301) |
|---|
| 27 | apps.each do |app, klass| |
|---|
| 28 | s.mount_proc("/#{app}") do |req, resp| |
|---|
| 29 | Object.instance_eval do |
|---|
| 30 | remove_const :ENV |
|---|
| 31 | const_set :ENV, req.meta_vars |
|---|
| 32 | end |
|---|
| 33 | def resp.<<(data) |
|---|
| 34 | raw_header, body = "#{data}".split(/^[\xd\xa]+/on, 2) |
|---|
| 35 | |
|---|
| 36 | begin |
|---|
| 37 | header = WEBrick::HTTPUtils::parse_header(raw_header) |
|---|
| 38 | if /^(\d+)/ =~ header['status'][0] |
|---|
| 39 | self.status = $1.to_i |
|---|
| 40 | header.delete('status') |
|---|
| 41 | end |
|---|
| 42 | header.each{|key, val| self[key] = val.join(", ") } |
|---|
| 43 | rescue => ex |
|---|
| 44 | raise WEBrick::HTTPStatus::InternalServerError, ex.message |
|---|
| 45 | end |
|---|
| 46 | self.body = body |
|---|
| 47 | end |
|---|
| 48 | Dir.chdir("#{dir}/#{app}") |
|---|
| 49 | klass.run((req.body and StringIO.new(req.body)), resp) |
|---|
| 50 | Dir.chdir(dir) |
|---|
| 51 | nil |
|---|
| 52 | end |
|---|
| 53 | end |
|---|
| 54 | trap(:INT) do |
|---|
| 55 | s.shutdown |
|---|
| 56 | end |
|---|
| 57 | s.start |
|---|