Permalink
Browse files

start removing router; tests pass, need to verify all examples still run

  • Loading branch information...
1 parent ec9116e commit 6fffbc7957db8153715b2f99c382922704cf85ea @dj2 dj2 committed May 7, 2012
@@ -1,129 +0,0 @@
-#!/usr/bin/env ruby
-# encoding: utf-8
-$:<< '../lib' << 'lib'
-
-require 'goliath'
-
-# Example demonstrating how to have an API acting as a router.
-# RackRoutes defines multiple uris and how to map them accordingly.
-# Some of these routes are redirected to other Goliath API.
-#
-# The reason why only the last API is being used by the Goliath Server
-# is because its name matches the filename.
-# All the APIs are available but by default the server will use the one
-# matching the file name.
-
-# Our custom Goliath API
-class HelloWorld < Goliath::API
- def response(env)
- [200, {}, "hello world!"]
- end
-end
-
-class PostHelloWorld < Goliath::API
- def response(env)
- [200, {}, "hello post world!"]
- end
-end
-
-class HeaderCollector < Goliath::API
- def on_headers(env, header)
- @headers ||= {}
- @headers.merge!(header)
- end
-
- def response(env)
- [200, {}, "headers: #{@headers.inspect}"]
- end
-end
-
-class HelloNumber < Goliath::API
- use Goliath::Rack::Params
- def response(env)
- [200, {}, "number #{params[:number]}!"]
- end
-end
-
-class BigNumber < Goliath::API
- use Goliath::Rack::Params
- def response(env)
- [200, {}, "big number #{params[:number]}!"]
- end
-end
-
-class Bonjour < Goliath::API
- def response(env)
- [200, {}, "bonjour!"]
- end
-end
-
-class Hola < Goliath::API
- use Goliath::Rack::Params
- use Goliath::Rack::Validation::RequiredParam, {:key => "foo"}
-
- def response(env)
- [200, {}, "hola! #{params}"]
- end
-end
-
-class Aloha < Goliath::API
- use Goliath::Rack::Validation::RequestMethod, %w(GET)
-
- def response(env)
- [200, {}, "Aloha"]
- end
-end
-
-class Version < Goliath::API
- def response(env)
- [200, {"Content-Type" => "text/html"}, ["Version 0.1"]]
- end
-end
-
-class SayMyName < Goliath::API
- def response(env)
- [200, {}, ["Hello #{@opts[:name]}"]]
- end
-end
-
-
-class RackRoutes < Goliath::API
-
- # map Goliath API to a specific path
- get "/hello_world", HelloWorld
- head "/hello_world", HelloWorld
- post "/hello_world", PostHelloWorld
-
- map "/bonjour", Bonjour
- map "/aloha", Aloha
-
- get '/name1', SayMyName, :api_options => {:name => "Leonard"}
- get '/name2', SayMyName, :api_options => {:name => "Helena"}
-
- # map Goliath API to a specific path and inject validation middleware
- # for this route only in addition to the middleware specified by the
- # API class itself
- map "/headers", HeaderCollector do
- use Goliath::Rack::Validation::RequestMethod, %w(GET)
- end
-
- map "/hola/:name", Hola do
- use Goliath::Rack::Validation::RequestMethod, %w(GET)
- end
-
- # bad route: you cannot run arbitrary procs or classes, please provide
- # an implementation of the Goliath API
- map "/bad_route", Hola do
- run Hola.new
- end
-
- not_found('/') do
- run Proc.new { |env| [404, {"Content-Type" => "text/html"}, ["Try /version /hello_world, /bonjour, or /hola"]] }
- end
-
- # You must use either maps or response, but never both!
- def response(env)
- raise RuntimeException.new("#response is ignored when using maps, so this exception won't raise. See spec/integration/rack_routes_spec.")
- end
-
-end
View
@@ -1,42 +0,0 @@
-#!/usr/bin/env ruby
-$:<< '../lib' << 'lib'
-
-require 'goliath'
-
-class ValidSingleParam < Goliath::API
- use Goliath::Rack::Params
- use Goliath::Rack::Validation::RequiredParam, {:key => 'test'}
-
- # If you are using Golaith version <=0.9.1 you need to use Goliath::Rack::ValidationError
- # to prevent the request from remaining open after an error occurs
- #use Goliath::Rack::ValidationError
-
- def response(env)
- [200, {}, 'OK']
- end
-end
-
-
-class ValidNestedParams < Goliath::API
- use Goliath::Rack::Params
-
- # For this validation to pass you need to have this as parameter (json body here)
- # {
- # 'data' : {
- # 'login' : 'my_login'
- # }
- # }
- #
- use Goliath::Rack::Validation::RequiredParam, :key => %w(data login)
-
- def response(env)
- [200, {}, 'OK']
- end
-end
-
-
-
-class Router < Goliath::API
- map '/valid_param1', ValidSingleParam
- map '/valid_param2', ValidNestedParams
-end
View
@@ -5,9 +5,11 @@
require 'goliath/websocket'
require 'goliath/rack/templates'
-require 'pp'
+class Websocket < Goliath::WebSocket
+ include Goliath::Rack::Templates
+
+ use Goliath::Rack::Favicon, File.expand_path(File.dirname(__FILE__) + '/ws/favicon.ico')
-class WebsocketEndPoint < Goliath::WebSocket
def on_open(env)
env.logger.info("WS OPEN")
env['subscription'] = env.channel.subscribe { |m| env.stream_send(m) }
@@ -26,19 +28,12 @@ def on_close(env)
def on_error(env, error)
env.logger.error error
end
-end
-
-class WSInfo < Goliath::API
- include Goliath::Rack::Templates
def response(env)
- [200, {}, erb(:index, :views => Goliath::Application.root_path('ws'))]
+ if env['REQUEST_PATH'] == '/ws'
+ super(env)
+ else
+ [200, {}, erb(:index, :views => Goliath::Application.root_path('ws'))]
+ end
end
-end
-
-class Websocket < Goliath::API
- use Goliath::Rack::Favicon, File.expand_path(File.dirname(__FILE__) + '/ws/favicon.ico')
-
- get '/', WSInfo
- map '/ws', WebsocketEndPoint
-end
+end
View
@@ -25,7 +25,6 @@ Gem::Specification.new do |s|
s.add_dependency 'rack-respond_to'
s.add_dependency 'async-rack'
s.add_dependency 'multi_json'
- s.add_dependency 'http_router', '~> 0.9.0'
s.add_development_dependency 'rake', '>=0.8.7'
s.add_development_dependency 'rspec', '>2.0'
View
@@ -1,4 +1,3 @@
-require 'http_router'
require 'goliath/goliath'
require 'goliath/response'
require 'goliath/request'
@@ -102,69 +101,6 @@ def plugins
def plugin(name, *args)
plugins.push([name, args])
end
-
- # Returns the router maps configured for the API
- #
- # @return [Array] array contains [path, klass, block]
- def maps
- @maps ||= []
- end
-
- def maps?
- !maps.empty?
- end
-
- # Specify a router map to be used by the API
- #
- # @example
- # map '/version', ApiClass
- #
- # @example
- # map '/version_get', ApiClass do
- # # inject GET validation middleware for this specific route
- # use Goliath::Rack::Validation::RequestMethod, %w(GET)
- # end
- #
- #
- # @param name [String] The URL path to map.
- # Optional parts are supported via <tt>(.:format)</tt>, variables as <tt>:var</tt> and globs via <tt>*remaining_path</tt>.
- # Variables can be validated by supplying a Regexp.
- # @param klass [Class] The class to retrieve the middlewares from
- # @param block The code to execute
- def map(name, *args, &block)
- opts = args.last.is_a?(Hash) ? args.pop : {}
- klass = args.first
- maps.push([name, klass, opts, block])
- end
-
- [:get, :post, :head, :put, :delete, :patch].each do |http_method|
- class_eval <<-EOT, __FILE__, __LINE__ + 1
- def #{http_method}(name, *args, &block)
- opts = args.last.is_a?(Hash) ? args.pop : {}
- klass = args.first
- opts[:conditions] ||= {}
- opts[:conditions][:request_method] = [#{http_method.to_s.upcase.inspect}]
- map(name, klass, opts, &block)
- end
- EOT
- end
-
- def router
- unless @router
- @router = HttpRouter.new
- @router.default(proc{ |env|
- @router.routes.last.dest.call(env)
- })
- end
- @router
- end
-
- # Use to define the 404 routing logic. As well, define any number of other paths to also run the not_found block.
- def not_found(*other_paths, &block)
- app = ::Rack::Builder.new(&block).to_app
- router.default(app)
- other_paths.each {|path| router.add(path).to(app) }
- end
end
##
@@ -297,20 +233,5 @@ def streaming_response(status_code = 200, headers = {})
def chunked_streaming_response(status_code = 200, headers = {})
streaming_response(status_code, headers.merge(Goliath::Response::CHUNKED_STREAM_HEADERS))
end
-
- # Helper method to initialize the approriate API handler
- #
- # Called by the parser once headers are available to detect
- # which API class should be handling the incoming request
- def set_event_handler!(env)
- if self.class.maps?
- response = self.class.router.recognize(env)
- if response = self.class.router.recognize(env) and response.respond_to?(:path) and response.path.route.api_class
- env.event_handler = response.path.route.api_class.new(response.path.route.api_options)
- end
- end
- env.event_handler ||= self
- end
-
end
end
@@ -9,10 +9,10 @@
# as it won't pickup the e flag.
env = ENV['RACK_ENV']
env ||= begin
- if ((i = ARGV.index('-e')) || (i = ARGV.index('--environment')))
- ARGV[i + 1]
- end
- end
+ if ((i = ARGV.index('-e')) || (i = ARGV.index('--environment')))
+ ARGV[i + 1]
+ end
+ end
Goliath.env = env if env
module Goliath
@@ -108,12 +108,11 @@ def self.run!
begin
klass = Kernel
- @app_class.split('::').each do |con|
- klass = klass.const_get(con)
- end
+ @app_class.split('::').each { |con| klass = klass.const_get(con) }
rescue NameError
raise NameError, "Class #{@app_class} not found."
end
+
api = klass.new
runner = Goliath::Runner.new(ARGV, api)
@@ -32,11 +32,9 @@ def post_init
r = Goliath::Request.new(@app, self, env)
r.parse_header(h, @parser) do
- @api.set_event_handler!(env) if @api
-
- env[ASYNC_HEADERS] = env.event_handler.method(:on_headers) if env.event_handler.respond_to? :on_headers
- env[ASYNC_BODY] = env.event_handler.method(:on_body) if env.event_handler.respond_to? :on_body
- env[ASYNC_CLOSE] = env.event_handler.method(:on_close) if env.event_handler.respond_to? :on_close
+ env[ASYNC_HEADERS] = api.method(:on_headers) if api.respond_to?(:on_headers)
+ env[ASYNC_BODY] = api.method(:on_body) if api.respond_to?(:on_body)
+ env[ASYNC_CLOSE] = api.method(:on_close) if api.respond_to?(:on_close)
end
@requests.push(r)
View
@@ -6,7 +6,6 @@ module Goliath
# Goliath::Env also provides access to the logger, configuration information
# and anything else set into the config data during initialization.
class Env < Hash
- attr_accessor :event_handler
include Constants
# Create a new Goliath::Env object
@@ -8,7 +8,6 @@
# The Goliath Framework
module Goliath
module_function
-
extend EnvironmentHelpers
# Retrieves the current goliath environment
@@ -22,13 +21,11 @@ def env
#
# @param [String|Symbol] env the environment symbol
def env=(e)
- es = case(e.to_sym)
+ @env = case(e.to_sym)
when :dev then :development
when :prod then :production
else e.to_sym
end
-
- @env = es
end
# Determines if we are in a particular environment
Oops, something went wrong.

3 comments on commit 6fffbc7

@inancgumus

Why did you remove this? How can I add routes now?

@inancgumus

https://groups.google.com/forum/m/?fromgroups#!topic/goliath-io/qhzbRyp6fCA

For anyone looking for a simpler solution: Grape + Goliath

But, he's (David) not sure about the performance/principles of this marriage.

Please sign in to comment.