Created
January 8, 2017 17:41
-
-
Save RX14/a733ba778343492e345ac63dc1a2a9d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "http" | |
require "radix" | |
class WebServer | |
alias Route = HTTP::Server::Context, Hash(String, String) -> Nil | |
def initialize(@config : Config, @db : DB::Database) | |
@tree = Radix::Tree(Route).new | |
draw_routes | |
spawn { run } | |
end | |
private def draw_routes | |
route "GET", "/satellites", SatelliteController.list | |
route "GET", "/passes", PassController.list | |
route "GET", "/passes/upcoming", PassController.list_upcoming | |
end | |
private def run | |
handlers = [ | |
HTTP::ErrorHandler.new, | |
HTTP::LogHandler.new, | |
] | |
server = HTTP::Server.new("0.0.0.0", 8080, handlers) do |context| | |
result = @tree.find("/#{context.request.method}#{context.request.path}") | |
if result.found? | |
result.payload.call(context, result.params) | |
else | |
context.response.status_code = 404 | |
context.response.content_type = "text/plain" | |
context.response.puts "Not Found" | |
end | |
end | |
puts "Listening on http://0.0.0.0:8080/" | |
server.listen | |
end | |
private def route(method, path, &route : Route) | |
@tree.add "/#{method}#{path}", route | |
end | |
private macro route(method, path, location) | |
route({{method}}, {{path}}) do |context, params| | |
%controller = {{location.receiver}}.new(context, params, @db) | |
%controller.{{location.name}} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment