Skip to content

Instantly share code, notes, and snippets.

@RX14
Created January 8, 2017 17:41
Show Gist options
  • Save RX14/a733ba778343492e345ac63dc1a2a9d4 to your computer and use it in GitHub Desktop.
Save RX14/a733ba778343492e345ac63dc1a2a9d4 to your computer and use it in GitHub Desktop.
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