Class: Gom::Remote::HttpServer

Inherits:
Object
  • Object
show all
Includes:
OAttr
Defined in:
lib/gom/remote/http_server.rb

Constant Summary collapse

Defaults =
{
  :host => "0.0.0.0", :port => 25191
}

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ HttpServer

Returns a new instance of HttpServer.



17
18
19
20
21
# File 'lib/gom/remote/http_server.rb', line 17

def initialize options = {}
  @options = (Defaults.merge options)
  @mounts = {}
  @mounts_access = Mutex.new
end

Instance Method Details

#base_urlObject



23
24
25
26
# File 'lib/gom/remote/http_server.rb', line 23

def base_url
  p = (port == 80 ? '' : ":#{port}")
  "http://#{host}#{p}"
end

#match(uri) ⇒ Object

take the URI on walk it through the list of mounts and return the one with the longest match or nil. In case of a match the corresponding handler is returned, nil otherwise.



66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/gom/remote/http_server.rb', line 66

def match uri
  targets = []
  @mounts_access.synchronize do
    targets = @mounts.map do |re, app|
      [app, (uri.path.match re).to_s]
    end
  end

  # sort for longest match. And target might be nil already for an empty
  # targets list, which is ok as we return nil in that case.
  target = targets.sort!{|a,b| a[1].length <=> b[1].length}.last
  func, pattern = target
  (pattern.nil? || pattern.empty?) ? nil : func
end

#mount(pattern, handler) ⇒ Object



32
33
34
35
# File 'lib/gom/remote/http_server.rb', line 32

def mount pattern, handler
  @mounts_access.synchronize { @mounts.update pattern => handler }
  self
end

#running?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/gom/remote/http_server.rb', line 28

def running?
  !@server.nil?
end

#startObject



42
43
44
45
46
47
# File 'lib/gom/remote/http_server.rb', line 42

def start
  @server.nil? or (raise "already running!")
  @thread = Thread.new { start_mongrel_server }
  sleep 0.1 # give thread time for start-up
  @thread
end

#stopObject



49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/gom/remote/http_server.rb', line 49

def stop
  @server.nil? and (raise "not running!")
  puts ' -- stopping callback server..'
  @server.stop
  @server = nil
  puts '    down.'
  sleep 2 # sleep added as a precaution 
  puts ' -- killing server thread now...'
  @thread.kill
  @thread = nil
  puts '    and gone.'
  self
end

#unmount(pattern) ⇒ Object



37
38
39
40
# File 'lib/gom/remote/http_server.rb', line 37

def unmount pattern
  @mounts_access.synchronize { @mounts.delete pattern }
  self
end