Skip to content

Instantly share code, notes, and snippets.

@onliniak
Created October 4, 2020 15:02
Show Gist options
  • Select an option

  • Save onliniak/c2fa3c035b83527a3fb94d03caa54b10 to your computer and use it in GitHub Desktop.

Select an option

Save onliniak/c2fa3c035b83527a3fb94d03caa54b10 to your computer and use it in GitHub Desktop.
Crystal router 2.0
require "./router.cr"
server = HTTP::Server.new(Router.new)
server.bind_tcp "127.0.0.1", 8080
server.listen
require "http/server"
class Router
include HTTP::Handler
macro route(a, b, c = " ", d = "text/plain")
if method == {{a}} &&
path == "/{{b}}"
context.response.content_type = {{d}}
{{b}}
context.response.print {{c}}
context.response.close
end
end
def initialize
end
def app
puts "Never fear, app is here"
end
def call(context)
method = context.request.method
path = context.request.path
route "GET", app, "Hello World!"
context.response.respond_with_status(500)
end
end
@onliniak
Copy link
Copy Markdown
Author

onliniak commented Oct 4, 2020

  1. I'm starting up the server
  2. All routes are managed by one macro.
  3. The macro executes the code of the same method as the path and then stops executing further code.
  4. If the route is not specified, the server returns error code 500.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment