Class: Musako::Cli::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/musako/cli/server.rb

Class Method Summary collapse

Class Method Details

.mime_typesObject



67
68
69
70
71
72
73
# File 'lib/musako/cli/server.rb', line 67

def self.mime_types
  mime_types_file = File.expand_path(
    '../mime.types',
    File.dirname(__FILE__)
  )
  WEBrick::HTTPUtils::load_mime_types(mime_types_file)
end

.process(options) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/musako/cli/server.rb', line 4

def self.process(options)
  require 'webrick'
  include WEBrick

  unless File.exists?(options[:destination])
    p "target dir is not found"
    return
  end

  # recreate NondisclosureName under utf-8 circumstance
  fh_option = WEBrick::Config::FileHandler
  fh_option[:NondisclosureName] = ['.ht*','~*']

  s = HTTPServer.new(webrick_options(options))
  s.mount(
    "/",
    HTTPServlet::FileHandler,
    options[:destination],
    fh_option
  )

  p "Server address: http://#{s.config[:BindAddress]}:#{s.config[:Port]}"

  if options[:detach]
    # detach the server
    pid = Process.fork { s.start }
    Process.detach(pid)
    p "Server detatched with pid '#{pid}'.", "Run `kill -9 #{pid}' to stop the server."
  else
    # create a new server thread, then join it with current terminal
    t = Thread.new { s.start }
    trap("INT") { s.shutdown }
    t.join()
  end
end

.start_callback(detached) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/musako/cli/server.rb', line 59

def self.start_callback(detached)
  unless detached
    Proc.new {
      p "Server running..., press ctrl-c to stop."
    }
  end
end

.webrick_options(config) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/musako/cli/server.rb', line 40

def self.webrick_options(config)
  opts = {
    :Port => config[:port],
    :BindAddress => config[:host],
    :MimeTypes => self.mime_types,
    :DoNotReverseLookup => true,
    :StartCallback => start_callback(config[:detach])
  }

  if !config[:verbose]
    opts.merge!({
      :AccessLog => [],
      :Logger => Log::new([], Log::WARN)
    })
  end

  opts
end