kemal/src/kemal.cr

76 lines
2 KiB
Crystal
Raw Normal View History

require "http"
2015-10-23 19:48:30 +00:00
require "./kemal/*"
require "./kemal/helpers/*"
2014-06-11 23:41:02 +00:00
2016-03-19 13:15:25 +00:00
module Kemal
# Overload of self.run with the default startup logging
def self.run(port = nil)
self.run port do
log "[#{config.env}] Kemal is ready to lead at #{config.scheme}://#{config.host_binding}:#{config.port}\n"
end
end
# Overload of self.run to allow just a block
def self.run(&block)
2017-02-06 17:16:51 +00:00
self.run nil, &block
end
2016-04-18 18:40:48 +00:00
# The command to run a `Kemal` application.
2016-09-20 23:32:09 +00:00
# The port can be given to `#run` but is optional.
# If not given Kemal will use `Kemal::Config#port`
def self.run(port = nil, &block)
2016-03-19 13:15:25 +00:00
Kemal::CLI.new
config = Kemal.config
config.setup
config.port = port if port
2015-11-16 21:55:02 +00:00
config.server = HTTP::Server.new(config.host_binding, config.port, config.handlers)
2016-09-20 23:32:09 +00:00
{% if !flag?(:without_openssl) %}
config.server.tls = config.ssl
{% end %}
2015-11-19 18:54:58 +00:00
unless Kemal.config.error_handlers.has_key?(404)
error 404 do |env|
render_404
end
2016-05-05 19:35:36 +00:00
end
2016-04-18 18:40:48 +00:00
# Test environment doesn't need to have signal trap, built-in images, and logging.
unless config.env == "test"
Signal::INT.trap {
log "Kemal is going to take a rest!\n" if config.shutdown_message
2016-12-08 10:50:54 +00:00
Kemal.stop
exit
}
2015-11-19 18:54:58 +00:00
# This route serves the built-in images for not_found and exceptions.
get "/__kemal__/:image" do |env|
image = env.params.url["image"]
2016-11-23 17:47:13 +00:00
file_path = File.expand_path("lib/kemal/images/#{image}", Dir.current)
if File.exists? file_path
send_file env, file_path
2016-11-25 19:19:23 +00:00
else
halt env, 404
2016-03-19 13:15:25 +00:00
end
end
end
config.running = true
yield config
config.server.listen if config.env != "test"
2015-11-28 10:39:58 +00:00
end
2016-12-08 10:50:54 +00:00
def self.stop
if config.running
if config.server
config.server.close
config.running = false
else
2016-12-08 19:15:18 +00:00
raise "Kemal.config.server is not set. Please use Kemal.run to set the server."
2016-12-08 10:50:54 +00:00
end
else
raise "Kemal is already stopped."
end
end
2016-03-19 13:15:25 +00:00
end