Skip to content

Instantly share code, notes, and snippets.

@onliniak
Last active September 30, 2020 15:50
Show Gist options
  • Save onliniak/2fa2b25f68dfc472c4bdcbadf8d543e1 to your computer and use it in GitHub Desktop.
Save onliniak/2fa2b25f68dfc472c4bdcbadf8d543e1 to your computer and use it in GitHub Desktop.
Simple Crystal router
Greeting, <%= @name %>!
require "http/server"
require "json"
require "./µPub/view"
server = HTTP::Server.new([
HTTP::LogHandler.new,
]) do |context|
req = context.request
res = context.response
if req.method == "GET" && req.path == "/foo"
query = req.query_params["test"]? || "" #=> http://0.0.0.0:8080/foo?test=test
res.headers["Server"] = "Crystal"
res.cookies["foo"] = HTTP::Cookie.new("foo", "bar", "/foo", Time.utc + 12.hours, secure: true)
res.content_type = "text/plain"
res.print "Hello world! #{query}" #=> Hello world! test
elsif req.method == "GET" && req.path == "/json"
res.content_type = "application/json"
res.print "Hello World!".to_json
elsif req.method == "POST" && req.path == "/john"
body = context.request.body.not_nil!.gets_to_end # Solved by: Kemal/param_parser
params = HTTP::Params.parse(body) #=> curl -X POST http://0.0.0.0:8080/john -d 'surname=Smith'
name = Greeting.new("John").to_s
surname = params["surname"]
res.content_type = "text/plain"
res.print "#{name} #{surname}" #=> Greeting, John! Smith
else
res.status_code = 500
end
end
address = server.bind_tcp "0.0.0.0", 8080
puts "Listening on http://#{address}"
server.listen
require "ecr"
class Greeting
def initialize(@name : String)
end
ECR.def_to_s "./greeting.ecr"
end
@onliniak
Copy link
Author

onliniak commented Sep 30, 2020

My server = FreeBSD11, my computer = Linux amd64.
I can't use Kermal because one uses 0.35 Crystal and the other 0.27.

The only option is to write the router myself or change language.
Though I wouldn't recommend it for non-small applications (above 10 routes).

PS: Warning: /john = memory leaks.

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