source: subversion/applications/utils/little-osm/server.rb @ 34318

Last change on this file since 34318 was 1227, checked in by imi, 13 years ago

extracted little-osm's data access library to osm-data

  • Property svn:executable set to *
File size: 2.1 KB
Line 
1#!/usr/bin/ruby
2# This is a small hand-made http server. (Why not use webbrick? Because it always
3# caches the whole response before sending it to the client.)
4
5$DEBUG = true
6
7require 'socket'
8require 'uri'
9
10$: << File.dirname(__FILE__)+"/../osm-data/lib"
11
12require 'osm/data'
13require 'osm/rexml'
14require 'tools'
15
16# use all api files here. For Debug mode, they will later be reloaded, so that
17# changes are in effect even if the server is not restarted.
18require 'api/map'
19require 'api/test'
20
21include OSM
22
23$stdout.sync = true if $-v
24
25puts "Start server on localhost:3000"
26server = TCPServer.new('127.0.0.1', 3000)
27loop do
28  session = server.accept
29  puts "connection accepted" if $-v
30  Thread.start(session) do |session|
31    uri = URI.parse session.gets.scan(/GET \/(.*) HTTP/)[0][0]
32    cmd = uri.path.scan(/[^\/]*/)[0]
33    cmd ||= "test"
34    puts Thread.current.object_id.to_s + ": call command '#{cmd}'" if $-v
35    queries_arr = uri.query.nil? ? [] : uri.query.split('&').collect do |x| x.split "=" end
36    queries = {}
37    queries_arr.each do |x| queries[x[0]] = (x[1] ||= "") end
38    begin
39      load "api/#{cmd}.rb" if $DEBUG # Reload the file, so that developers can change it on running server
40      catch :little_osm_done do
41        eval "OSM::#{cmd}(uri, queries, session)"
42      end
43    rescue => x
44      puts Thread.current.object_id.to_s + ": Error while executing #{cmd}: #{x}" if $-v
45      # If the error occoured after the api call sent the ok-header, this would not make much sense, but
46      # it is the best hint we can give to the client in an unbuffered server response.. (and hopefully,
47      # this will invalidate every xml structure making the response unlikely to be misinterpreted ;)
48      session << "HTTP/1.1 500/Exception executing script\r\n"
49      session << "Server: little-osm\r\n"
50      session << "Content-type: text/plain\r\n\r\n"
51      session << "Error while executing script #{cmd}.rb:\r\n"
52      session << "#{x}\r\n  "
53      session << x.backtrace.join("\r\n  ")
54    ensure
55      puts Thread.current.object_id.to_s + ": call finished" if $-v
56      session.close
57    end
58  end
59end
Note: See TracBrowser for help on using the repository browser.