Skip to content

Instantly share code, notes, and snippets.

@al3rez
Created December 13, 2017 19:00
Show Gist options
  • Save al3rez/5099b497ef67eb4dca317b4e8439bb95 to your computer and use it in GitHub Desktop.
Save al3rez/5099b497ef67eb4dca317b4e8439bb95 to your computer and use it in GitHub Desktop.
Building a RESTful API with Crystal
require "http/server"
class Users::Me
include HTTP::Handler
def call(context)
return call_next(context) unless match?(context.request)
STDOUT.puts "getting user info..."
STDOUT.puts "done!"
end
def match?(request : HTTP::Request)
request.resource == "/users/me" && request.method == "GET"
end
end
class Users::Create
include HTTP::Handler
def call(context)
return call_next(context) unless match?(context.request)
STDOUT.puts "creating user..."
STDOUT.puts "done!"
end
def match?(request : HTTP::Request)
request.resource == "/users" && request.method == "POST"
end
end
class Users::Update
include HTTP::Handler
def call(context)
return call_next(context) unless match?(context.request)
STDOUT.puts "updating user..."
STDOUT.puts "done!"
end
def match?(request : HTTP::Request)
request.resource == "/users" && request.method == "PUT"
end
end
class Users::UpdatePartially
include HTTP::Handler
def call(context)
return call_next(context) unless match?(context.request)
STDOUT.puts "updating user partially..."
STDOUT.puts "done!"
end
def match?(request : HTTP::Request)
request.resource == "/users" && request.method == "PUT"
end
end
class Users::Destroy
include HTTP::Handler
def call(context)
return call_next(context) unless match?(context.request)
STDOUT.puts "destroying user..."
STDOUT.puts "done!"
end
def match?(request : HTTP::Request)
request.resource == "/users" && request.method == "DELETE"
end
end
HTTP::Server.new("127.0.0.1", 8080, [
HTTP::LogHandler.new,
Users::Me.new,
Users::Create.new,
Users::Update.new,
Users::UpdatePartially.new,
Users::Destroy.new,
]).listen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment