Last active
August 29, 2015 14:03
-
-
Save pachacamac/2391af75ba205f99b8db to your computer and use it in GitHub Desktop.
busker - a minimal, sinatra inspired, webrick based (only using ruby-std lib stuff), web app framework that wants to remain easy and platform independent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'webrick' | |
require 'cgi' | |
class Busker | |
def initialize(opts={}, &block) | |
@routes = {} | |
(block.arity < 1 ? instance_eval(&block) : block.call(self)) if block_given? | |
opts[:Port] ||= opts.delete(:port) || 8080 | |
opts[:DocumentRoot] ||= opts.delete(:document_root) || File.expand_path('./') | |
@server = WEBrick::HTTPServer.new(opts) | |
@server.mount_proc '' do |req, res| | |
begin | |
res.status, res.content_type, method = nil, 'text/html', req.request_method.tr('-', '_').upcase | |
route, handler = @routes.find{|k,v| k[0].include?(method) && k[1].match(req.path_info)} | |
params = Hash[CGI::parse(req.query_string||'').map{|k,v| [k.to_sym,v[0]]} + $~.names.map(&:to_sym).zip($~.captures)] | |
res.status, res.body = route ? [res.status || 200, handler[:block].call(params, req, res)] : [404, 'not found'] | |
rescue => e | |
@server.logger.error "#{e.message}\n#{e.backtrace.map{|line| "\t#{line}"}.join("\n")}" | |
res.status, res.body = 500, "#{e}" | |
end | |
end | |
end | |
def route(path, methods = ['GET'], opts={}, &block) | |
methods = (methods.is_a?(Array) ? methods : [methods]).map{|e| e.to_s.tr('-', '_').upcase} | |
path.gsub!(/(:\w+)/){|m| "(?<#{$1[1..-1]}>\\w+)"} | |
@routes[[methods, Regexp.new("\\A#{path}\\Z")]] = {:opts => opts, :block => block} | |
end | |
def start | |
@server.start ensure @server.shutdown | |
end | |
end | |
require 'pp' | |
b = Busker.new(:port => 8000) do | |
route '/info/?', [:GET, :POST] do |params, req, res| | |
res.content_type = 'text/plain' | |
req.pretty_inspect | |
end | |
route '/foo/?', :GET do |params| | |
"foo is working #{params}" | |
end | |
route '/fail/?' do | |
7/0 | |
end | |
route '/foo/:id/bar/?' do |params| | |
params[:id] | |
end | |
end | |
b.route('/test'){'Juhu'} | |
b.start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment