router
router
Installation
Add this to your application's shard.yml
:
dependencies:
router:
github: sourceweaver/router
version: 0.1.2
Usage
Basic usage
require "router"
Include Router
to utilize router.
class WebServer
include Router
end
Define a method to draw all routes for your web server.
class WebServer
include Router
def draw_routes
# Drawing routes HERE!
end
end
In that method, call HTTP method name (downcase) like get
or post
with PATH and BLOCK where
- PATH : String
- BLOCK : block of HTTP::Server::Context, Hash(String, String) -> HTTP::Server::Context
class WebServer
include Router
def draw_routes
get "/" do |context, params|
context.response.print "Hello router!"
context
end
end
end
Here we've defined a GET route at root path (/) that just print out "Hello router" when we get access. To activate (run) the route, just define run methods for your server with route_handler
class WebServer
include Router
def draw_routes
get "/" do |context, params|
context.response.print "Hello router!"
context
end
end
def run
server = HTTP::Server.new(route_handler)
server.bind_tcp 8080
server.listen
end
end
Here route_handler is getter defined in Router. So you can call route_handler
at anywhere in WebServer instance.
Finally, run your server.
web_server = WebServer.new
web_server.draw_routes
web_server.run
See samples and tips for details.
Path parameters
params
is a Hash(String, String) that is used when you define a path parameters such as /user/:id
(:id
is the parameter). Here is an example.
class WebServer
include Router
def draw_routes
get "/user/:id" do |context, params|
context.response.print params["id"] # get :id in url from params
context
end
end
end
See samples and tips for details.
License
router is a fork of router.cr. Both projects are MIT licensed.
router
- 0
- 0
- 0
- 0
- 1
- about 2 years ago
- October 13, 2022
MIT License
Fri, 22 Nov 2024 01:18:08 GMT