Skip to content
This repository
Browse code

Merge branch 'nuke_router' of github.com:postrank-labs/goliath

  • Loading branch information...
commit c53d8a44a6dc850c498fecbee535f4aae3dcc12b 2 parents 951ae62 + 7e841ba
Ilya Grigorik authored May 10, 2012
10  examples/api_proxy.rb
@@ -4,8 +4,8 @@
4 4
 
5 5
 require 'goliath'
6 6
 require 'em-synchrony/em-http'
7  
- 
8  
-class TwilioResponse < Goliath::API
  7
+
  8
+class Twilio < Goliath::API
9 9
   use Goliath::Rack::Params
10 10
   use Goliath::Rack::JSONP
11 11
 
@@ -18,11 +18,7 @@ def response(env)
18 18
 
19 19
     http = EM::HttpRequest.new(url).get head: HEADERS
20 20
     logger.debug "Received #{http.response_header.status} from Twilio"
21  
- 
  21
+
22 22
     [200, {'X-Goliath' => 'Proxy','Content-Type' => 'application/javascript'}, http.response]
23 23
   end
24 24
 end
25  
-
26  
-class Twilio < Goliath::API
27  
-  get %r{^/(Local|TollFree)}, TwilioResponse
28  
-end
13  examples/custom_server.rb
@@ -7,23 +7,12 @@
7 7
 # Example demonstrating how to use a custom Goliath runner
8 8
 #
9 9
 
10  
-class Hello < Goliath::API
  10
+class Custom < Goliath::API
11 11
   def response(env)
12 12
     [200, {}, "hello!"]
13 13
   end
14 14
 end
15 15
 
16  
-class Bonjour < Goliath::API
17  
-  def response(env)
18  
-    [200, {}, "bonjour!"]
19  
-  end
20  
-end
21  
-
22  
-class Custom < Goliath::API
23  
-  map "/hello", Hello
24  
-  map "/bonjour", Bonjour
25  
-end
26  
-
27 16
 runner = Goliath::Runner.new(ARGV, nil)
28 17
 runner.api = Custom.new
29 18
 runner.app = Goliath::Rack::Builder.build(Custom, runner.api)
129  examples/rack_routes.rb
... ...
@@ -1,129 +0,0 @@
1  
-#!/usr/bin/env ruby
2  
-# encoding: utf-8
3  
-$:<< '../lib' << 'lib'
4  
-
5  
-require 'goliath'
6  
-
7  
-# Example demonstrating how to have an API acting as a router.
8  
-# RackRoutes defines multiple uris and how to map them accordingly.
9  
-# Some of these routes are redirected to other Goliath API.
10  
-#
11  
-# The reason why only the last API is being used by the Goliath Server
12  
-# is because its name matches the filename.
13  
-# All the APIs are available but by default the server will use the one
14  
-# matching the file name.
15  
-
16  
-# Our custom Goliath API
17  
-class HelloWorld < Goliath::API
18  
-  def response(env)
19  
-    [200, {}, "hello world!"]
20  
-  end
21  
-end
22  
-
23  
-class PostHelloWorld < Goliath::API
24  
-  def response(env)
25  
-    [200, {}, "hello post world!"]
26  
-  end
27  
-end
28  
-
29  
-class HeaderCollector < Goliath::API
30  
-  def on_headers(env, header)
31  
-    @headers ||= {}
32  
-    @headers.merge!(header)
33  
-  end
34  
-
35  
-  def response(env)
36  
-    [200, {}, "headers: #{@headers.inspect}"]
37  
-  end
38  
-end
39  
-
40  
-class HelloNumber < Goliath::API
41  
-  use Goliath::Rack::Params
42  
-  def response(env)
43  
-    [200, {}, "number #{params[:number]}!"]
44  
-  end
45  
-end
46  
-
47  
-class BigNumber < Goliath::API
48  
-  use Goliath::Rack::Params
49  
-  def response(env)
50  
-    [200, {}, "big number #{params[:number]}!"]
51  
-  end
52  
-end
53  
-
54  
-class Bonjour < Goliath::API
55  
-  def response(env)
56  
-    [200, {}, "bonjour!"]
57  
-  end
58  
-end
59  
-
60  
-class Hola < Goliath::API
61  
-  use Goliath::Rack::Params
62  
-  use Goliath::Rack::Validation::RequiredParam, {:key => "foo"}
63  
-
64  
-  def response(env)
65  
-    [200, {}, "hola! #{params}"]
66  
-  end
67  
-end
68  
-
69  
-class Aloha < Goliath::API
70  
-  use Goliath::Rack::Validation::RequestMethod, %w(GET)
71  
-
72  
-  def response(env)
73  
-    [200, {}, "Aloha"]
74  
-  end
75  
-end
76  
-
77  
-class Version < Goliath::API
78  
-  def response(env)
79  
-    [200, {"Content-Type" => "text/html"}, ["Version 0.1"]]
80  
-  end
81  
-end
82  
-
83  
-class SayMyName < Goliath::API
84  
-  def response(env)
85  
-    [200, {}, ["Hello #{@opts[:name]}"]]
86  
-  end
87  
-end
88  
-
89  
-
90  
-class RackRoutes < Goliath::API
91  
-
92  
-  # map Goliath API to a specific path
93  
-  get  "/hello_world", HelloWorld
94  
-  head "/hello_world", HelloWorld
95  
-  post "/hello_world", PostHelloWorld
96  
-
97  
-  map "/bonjour", Bonjour
98  
-  map "/aloha", Aloha
99  
-
100  
-  get '/name1', SayMyName, :api_options => {:name => "Leonard"}
101  
-  get '/name2', SayMyName, :api_options => {:name => "Helena"}
102  
-
103  
-  # map Goliath API to a specific path and inject validation middleware
104  
-  # for this route only in addition to the middleware specified by the
105  
-  # API class itself
106  
-  map "/headers", HeaderCollector do
107  
-    use Goliath::Rack::Validation::RequestMethod, %w(GET)
108  
-  end
109  
-
110  
-  map "/hola/:name", Hola do
111  
-    use Goliath::Rack::Validation::RequestMethod, %w(GET)
112  
-  end
113  
-
114  
-  # bad route: you cannot run arbitrary procs or classes, please provide
115  
-  # an implementation of the Goliath API
116  
-  map "/bad_route", Hola do
117  
-    run Hola.new
118  
-  end
119  
-
120  
-  not_found('/') do
121  
-    run Proc.new { |env| [404, {"Content-Type" => "text/html"}, ["Try /version /hello_world, /bonjour, or /hola"]] }
122  
-  end
123  
-
124  
-  # You must use either maps or response, but never both!
125  
-  def response(env)
126  
-    raise RuntimeException.new("#response is ignored when using maps, so this exception won't raise. See spec/integration/rack_routes_spec.")
127  
-  end
128  
-
129  
-end
25  examples/superclass_middleware.rb
... ...
@@ -1,25 +0,0 @@
1  
-#!/usr/bin/env ruby
2  
-$:<< '../lib' << 'lib'
3  
-
4  
-require 'goliath'
5  
-require 'yajl'
6  
-
7  
-class Base < Goliath::API
8  
-  use Goliath::Rack::Params
9  
-  use Goliath::Rack::Render, 'json'
10  
-
11  
-  def response(env)
12  
-    [200, {}, {:p => params}]
13  
-  end
14  
-end
15  
-
16  
-class Extend < Base
17  
-  def response(env)
18  
-    [200, {}, params]
19  
-  end
20  
-end
21  
-
22  
-class Router < Goliath::API
23  
-  map '/base', Base
24  
-  map '/extend', Extend
25  
-end
42  examples/valid.rb
... ...
@@ -1,42 +0,0 @@
1  
-#!/usr/bin/env ruby
2  
-$:<< '../lib' << 'lib'
3  
-
4  
-require 'goliath'
5  
-
6  
-class ValidSingleParam < Goliath::API
7  
-  use Goliath::Rack::Params
8  
-  use Goliath::Rack::Validation::RequiredParam, {:key => 'test'}
9  
-
10  
-  # If you are using Golaith version <=0.9.1 you need to use Goliath::Rack::ValidationError
11  
-  # to prevent the request from remaining open after an error occurs
12  
-  #use Goliath::Rack::ValidationError
13  
-
14  
-  def response(env)
15  
-    [200, {}, 'OK']
16  
-  end
17  
-end
18  
-
19  
-
20  
-class ValidNestedParams < Goliath::API
21  
-  use Goliath::Rack::Params
22  
-  
23  
-  # For this validation to pass you need to have this as parameter (json body here)
24  
-  # {
25  
-  #   'data' : {
26  
-  #     'login' : 'my_login'
27  
-  #   }
28  
-  # }
29  
-  # 
30  
-  use Goliath::Rack::Validation::RequiredParam, :key => %w(data login)
31  
-  
32  
-  def response(env)
33  
-    [200, {}, 'OK']
34  
-  end
35  
-end
36  
-
37  
-
38  
-
39  
-class Router < Goliath::API
40  
-  map '/valid_param1', ValidSingleParam
41  
-  map '/valid_param2', ValidNestedParams
42  
-end
25  examples/websocket.rb
@@ -5,9 +5,11 @@
5 5
 require 'goliath/websocket'
6 6
 require 'goliath/rack/templates'
7 7
 
8  
-require 'pp'
  8
+class Websocket < Goliath::WebSocket
  9
+  include Goliath::Rack::Templates
  10
+
  11
+  use Goliath::Rack::Favicon, File.expand_path(File.dirname(__FILE__) + '/ws/favicon.ico')
9 12
 
10  
-class WebsocketEndPoint < Goliath::WebSocket
11 13
   def on_open(env)
12 14
     env.logger.info("WS OPEN")
13 15
     env['subscription'] = env.channel.subscribe { |m| env.stream_send(m) }
@@ -26,19 +28,12 @@ def on_close(env)
26 28
   def on_error(env, error)
27 29
     env.logger.error error
28 30
   end
29  
-end
30  
-
31  
-class WSInfo < Goliath::API
32  
-  include Goliath::Rack::Templates
33 31
 
34 32
   def response(env)
35  
-    [200, {}, erb(:index, :views => Goliath::Application.root_path('ws'))]
  33
+    if env['REQUEST_PATH'] == '/ws'
  34
+      super(env)
  35
+    else
  36
+      [200, {}, erb(:index, :views => Goliath::Application.root_path('ws'))]
  37
+    end
36 38
   end
37  
-end
38  
-
39  
-class Websocket < Goliath::API
40  
-  use Goliath::Rack::Favicon, File.expand_path(File.dirname(__FILE__) + '/ws/favicon.ico')
41  
-
42  
-  get '/', WSInfo
43  
-  map '/ws', WebsocketEndPoint
44  
-end
  39
+end
3  goliath.gemspec
@@ -25,7 +25,6 @@ Gem::Specification.new do |s|
25 25
   s.add_dependency 'rack-respond_to'
26 26
   s.add_dependency 'async-rack'
27 27
   s.add_dependency 'multi_json'
28  
-  s.add_dependency 'http_router', '~> 0.9.0'
29 28
 
30 29
   s.add_development_dependency 'rake', '>=0.8.7'
31 30
   s.add_development_dependency 'rspec', '>2.0'
@@ -48,7 +47,7 @@ Gem::Specification.new do |s|
48 47
 
49 48
   if RUBY_PLATFORM.include?('darwin')
50 49
     s.add_development_dependency 'growl',       '~> 1.0.3'
51  
-    s.add_development_dependency 'rb-fsevent',  '0.4.3.1'
  50
+    s.add_development_dependency 'rb-fsevent'
52 51
   end
53 52
 
54 53
   ignores = File.readlines(".gitignore").grep(/\S+/).map {|s| s.chomp }
88  lib/goliath/api.rb
... ...
@@ -1,4 +1,3 @@
1  
-require 'http_router'
2 1
 require 'goliath/goliath'
3 2
 require 'goliath/response'
4 3
 require 'goliath/request'
@@ -36,15 +35,6 @@ def inherited(subclass)
36 35
       def middlewares
37 36
         @middlewares ||= []
38 37
 
39  
-        unless @loaded_superclass_middlewares
40  
-          if self.superclass != Goliath::API
41  
-            @middlewares = self.superclass.middlewares + @middlewares
42  
-            @middlewares = @middlewares.uniq
43  
-          end
44  
-
45  
-          @loaded_superclass_middlewares = true
46  
-        end
47  
-
48 38
         unless @loaded_default_middlewares
49 39
           @middlewares.unshift([::Goliath::Rack::DefaultResponseFormat, nil, nil])
50 40
           @middlewares.unshift([::Rack::ContentLength, nil, nil])
@@ -102,69 +92,6 @@ def plugins
102 92
       def plugin(name, *args)
103 93
         plugins.push([name, args])
104 94
       end
105  
-
106  
-      # Returns the router maps configured for the API
107  
-      #
108  
-      # @return [Array] array contains [path, klass, block]
109  
-      def maps
110  
-        @maps ||= []
111  
-      end
112  
-
113  
-      def maps?
114  
-        !maps.empty?
115  
-      end
116  
-
117  
-      # Specify a router map to be used by the API
118  
-      #
119  
-      # @example
120  
-      #  map '/version', ApiClass
121  
-      #
122  
-      # @example
123  
-      #  map '/version_get', ApiClass do
124  
-      #    # inject GET validation middleware for this specific route
125  
-      #    use Goliath::Rack::Validation::RequestMethod, %w(GET)
126  
-      #  end
127  
-      #
128  
-      #
129  
-      # @param name [String] The URL path to map.
130  
-      #   Optional parts are supported via <tt>(.:format)</tt>, variables as <tt>:var</tt> and globs via <tt>*remaining_path</tt>.
131  
-      #   Variables can be validated by supplying a Regexp.
132  
-      # @param klass [Class] The class to retrieve the middlewares from
133  
-      # @param block The code to execute
134  
-      def map(name, *args, &block)
135  
-        opts = args.last.is_a?(Hash) ? args.pop : {}
136  
-        klass = args.first
137  
-        maps.push([name, klass, opts, block])
138  
-      end
139  
-
140  
-      [:get, :post, :head, :put, :delete, :patch].each do |http_method|
141  
-        class_eval <<-EOT, __FILE__, __LINE__ + 1
142  
-        def #{http_method}(name, *args, &block)
143  
-          opts = args.last.is_a?(Hash) ? args.pop : {}
144  
-          klass = args.first
145  
-          opts[:conditions] ||= {}
146  
-          opts[:conditions][:request_method] = [#{http_method.to_s.upcase.inspect}]
147  
-          map(name, klass, opts, &block)
148  
-        end
149  
-        EOT
150  
-      end
151  
-
152  
-      def router
153  
-        unless @router
154  
-          @router = HttpRouter.new
155  
-          @router.default(proc{ |env|
156  
-            @router.routes.last.dest.call(env)
157  
-          })
158  
-        end
159  
-        @router
160  
-      end
161  
-
162  
-      # Use to define the 404 routing logic. As well, define any number of other paths to also run the not_found block.
163  
-      def not_found(*other_paths, &block)
164  
-        app = ::Rack::Builder.new(&block).to_app
165  
-        router.default(app)
166  
-        other_paths.each {|path| router.add(path).to(app) }
167  
-      end
168 95
     end
169 96
 
170 97
     ##
@@ -297,20 +224,5 @@ def streaming_response(status_code = 200, headers = {})
297 224
     def chunked_streaming_response(status_code = 200, headers = {})
298 225
       streaming_response(status_code, headers.merge(Goliath::Response::CHUNKED_STREAM_HEADERS))
299 226
     end
300  
-
301  
-    # Helper method to initialize the approriate API handler
302  
-    #
303  
-    # Called by the parser once headers are available to detect
304  
-    # which API class should be handling the incoming request
305  
-    def set_event_handler!(env)
306  
-      if self.class.maps?
307  
-        response = self.class.router.recognize(env)
308  
-        if response = self.class.router.recognize(env) and response.respond_to?(:path) and response.path.route.api_class
309  
-          env.event_handler = response.path.route.api_class.new(response.path.route.api_options)
310  
-        end
311  
-      end
312  
-      env.event_handler ||= self
313  
-    end
314  
-
315 227
   end
316 228
 end
13  lib/goliath/application.rb
@@ -9,10 +9,10 @@
9 9
 # as it won't pickup the e flag.
10 10
 env = ENV['RACK_ENV']
11 11
 env ||= begin
12  
-          if ((i = ARGV.index('-e')) || (i = ARGV.index('--environment')))
13  
-            ARGV[i + 1]
14  
-          end
15  
-        end
  12
+      if ((i = ARGV.index('-e')) || (i = ARGV.index('--environment')))
  13
+        ARGV[i + 1]
  14
+      end
  15
+    end
16 16
 Goliath.env = env if env
17 17
 
18 18
 module Goliath
@@ -108,12 +108,11 @@ def self.run!
108 108
 
109 109
       begin
110 110
         klass = Kernel
111  
-        @app_class.split('::').each do |con|
112  
-          klass = klass.const_get(con)
113  
-        end
  111
+        @app_class.split('::').each { |con| klass = klass.const_get(con) }
114 112
       rescue NameError
115 113
         raise NameError, "Class #{@app_class} not found."
116 114
       end
  115
+
117 116
       api = klass.new
118 117
 
119 118
       runner = Goliath::Runner.new(ARGV, api)
8  lib/goliath/connection.rb
@@ -32,11 +32,9 @@ def post_init
32 32
 
33 33
         r = Goliath::Request.new(@app, self, env)
34 34
         r.parse_header(h, @parser) do
35  
-          @api.set_event_handler!(env) if @api
36  
-
37  
-          env[ASYNC_HEADERS] = env.event_handler.method(:on_headers) if env.event_handler.respond_to? :on_headers
38  
-          env[ASYNC_BODY]    = env.event_handler.method(:on_body)    if env.event_handler.respond_to? :on_body
39  
-          env[ASYNC_CLOSE]   = env.event_handler.method(:on_close)   if env.event_handler.respond_to? :on_close
  35
+          env[ASYNC_HEADERS] = api.method(:on_headers) if api.respond_to?(:on_headers)
  36
+          env[ASYNC_BODY]    = api.method(:on_body)    if api.respond_to?(:on_body)
  37
+          env[ASYNC_CLOSE]   = api.method(:on_close)   if api.respond_to?(:on_close)
40 38
         end
41 39
 
42 40
         @requests.push(r)
1  lib/goliath/env.rb
@@ -6,7 +6,6 @@ module Goliath
6 6
   # Goliath::Env also provides access to the logger, configuration information
7 7
   # and anything else set into the config data during initialization.
8 8
   class Env < Hash
9  
-    attr_accessor :event_handler
10 9
     include Constants
11 10
 
12 11
     # Create a new Goliath::Env object
5  lib/goliath/goliath.rb
@@ -8,7 +8,6 @@
8 8
 # The Goliath Framework
9 9
 module Goliath
10 10
   module_function
11  
-
12 11
   extend EnvironmentHelpers
13 12
 
14 13
   # Retrieves the current goliath environment
@@ -22,13 +21,11 @@ def env
22 21
   #
23 22
   # @param [String|Symbol] env the environment symbol
24 23
   def env=(e)
25  
-    es = case(e.to_sym)
  24
+    @env = case(e.to_sym)
26 25
     when :dev  then :development
27 26
     when :prod then :production
28 27
     else e.to_sym
29 28
     end
30  
-
31  
-    @env = es
32 29
   end
33 30
 
34 31
   # Determines if we are in a particular environment
48  lib/goliath/rack/builder.rb
... ...
@@ -1,20 +1,9 @@
1  
-require 'http_router'
2  
-
3  
-class HttpRouter::Route
4  
-  attr_accessor :api_class, :api_options
5  
-end
6  
-
7 1
 module Goliath
8 2
   module Rack
9 3
     class Builder < ::Rack::Builder
10 4
       attr_accessor :params
11 5
       include Params::Parser
12 6
 
13  
-      alias_method :original_run, :run
14  
-      def run(app)
15  
-        raise "run disallowed: please mount a Goliath API class"
16  
-      end
17  
-
18 7
       # Builds the rack middleware chain for the given API
19 8
       #
20 9
       # @param klass [Class] The API class to build the middlewares for
@@ -25,42 +14,7 @@ def self.build(klass, api)
25 14
           klass.middlewares.each do |mw_klass, args, blk|
26 15
             use(mw_klass, *args, &blk)
27 16
           end
28  
-
29  
-          if klass.maps?
30  
-            klass.maps.each do |path, route_klass, opts, blk|
31  
-              route = klass.router.add(path, opts.dup)
32  
-              route.api_options = opts.delete(:api_options) || {}
33  
-              route.api_class = route_klass
34  
-
35  
-              route.to do |env|
36  
-                builder = Builder.new
37  
-
38  
-                env['params'] ||= {}
39  
-                if env['router.params']
40  
-                  env['router.params'].each {|k,v| env['params'][k.to_s] = v}
41  
-                end
42  
-
43  
-                builder.params = builder.retrieve_params(env)
44  
-                builder.instance_eval(&blk) if blk
45  
-
46  
-                if route_klass
47  
-                  route_klass.middlewares.each do |mw|
48  
-                    builder.instance_eval { use mw[0], *mw[1], &mw[2] }
49  
-                  end
50  
-                end
51  
-
52  
-                if route_klass or blk.nil?
53  
-                  builder.instance_eval { original_run env.event_handler }
54  
-                end
55  
-
56  
-                builder.to_app.call(env)
57  
-              end
58  
-            end
59  
-
60  
-            original_run klass.router
61  
-          else
62  
-            original_run api
63  
-          end
  17
+          run api
64 18
         end
65 19
       end
66 20
     end
2  lib/goliath/rack/params.rb
@@ -42,10 +42,8 @@ def retrieve_params(env)
42 42
                 post_params = {}
43 43
               end
44 44
             end
45  
-
46 45
             params.merge!(post_params)
47 46
           end
48  
-
49 47
           params
50 48
         end
51 49
       end
2  lib/goliath/response.rb
@@ -59,10 +59,8 @@ def headers=(key_value_pairs)
59 59
 
60 60
         if vs.is_a?(String)
61 61
           vs.each_line { |v| @headers[k] = v.chomp }
62  
-
63 62
         elsif vs.is_a?(Time)
64 63
           @headers[k] = vs
65  
-
66 64
         else
67 65
           vs.each { |v| @headers[k] = v.chomp }
68 66
         end
5  lib/goliath/websocket.rb
@@ -62,19 +62,16 @@ def close_connection_after_writing
62 62
         def send_data(data)
63 63
           @stream_send.call(data)
64 64
         end
65  
-
66 65
       end.new(env, self, old_stream_send, old_stream_close)
67 66
 
68 67
       upgrade_data = env[UPGRADE_DATA]
69  
-
70 68
       begin
71 69
         env['handler'] = EM::WebSocket::HandlerFactory.build_with_request(conn, request,
72  
-                                                                          upgrade_data, false, false)
  70
+            upgrade_data, false, false)
73 71
       rescue Exception => e
74 72
         env.logger.error("#{e.message}\n#{e.backtrace.join("\n")}")
75 73
         return [500, {}, {:error => "Upgrade failed"}]
76 74
       end
77  
-
78 75
       env['handler'].run
79 76
 
80 77
       Goliath::Connection::AsyncResponse
176  spec/integration/rack_routes_spec.rb
... ...
@@ -1,176 +0,0 @@
1  
-# encoding: utf-8
2  
-require 'spec_helper'
3  
-require File.join(File.dirname(__FILE__), '../../', 'examples/rack_routes')
4  
-
5  
-describe RackRoutes do
6  
-  let(:err) { Proc.new { fail "API request failed" } }
7  
-
8  
-  context "when using maps" do
9  
-
10  
-    it "ignores #response" do
11  
-      expect {
12  
-        with_api(RackRoutes) do
13  
-          get_request({:path => '/'}, err) {}
14  
-        end
15  
-      }.to_not raise_error
16  
-    end
17  
-
18  
-    it 'fallback not found to missing' do
19  
-      with_api(RackRoutes) do
20  
-        get_request({:path => '/donkey'}, err) do |cb|
21  
-          cb.response_header.status.should == 404
22  
-          cb.response.should == 'Try /version /hello_world, /bonjour, or /hola'
23  
-        end
24  
-      end
25  
-
26  
-      with_api(RackRoutes) do
27  
-        get_request({:path => '/'}, err) do |cb|
28  
-          cb.response_header.status.should == 404
29  
-          cb.response.should == 'Try /version /hello_world, /bonjour, or /hola'
30  
-        end
31  
-      end
32  
-    end
33  
-
34  
-    it 'fallback not found to /' do
35  
-      with_api(RackRoutes) do
36  
-        get_request({:path => '/donkey'}, err) do |cb|
37  
-          cb.response_header.status.should == 404
38  
-          cb.response.should == 'Try /version /hello_world, /bonjour, or /hola'
39  
-        end
40  
-      end
41  
-    end
42  
-
43  
-    it 'can pass options to api contructor' do
44  
-      with_api(RackRoutes) do
45  
-        get_request({:path => '/name1'}, err) do |cb|
46  
-          cb.response_header.status.should == 200
47  
-          cb.response.should == 'Hello Leonard'
48  
-        end
49  
-      end
50  
-
51  
-      with_api(RackRoutes) do
52  
-        get_request({:path => '/name2'}, err) do |cb|
53  
-          cb.response_header.status.should == 200
54  
-          cb.response.should == 'Hello Helena'
55  
-        end
56  
-      end
57  
-    end
58  
-
59  
-    it 'routes to the correct API' do
60  
-      with_api(RackRoutes) do
61  
-        get_request({:path => '/bonjour'}, err) do |c|
62  
-          c.response_header.status.should == 200
63  
-          c.response.should == 'bonjour!'
64  
-        end
65  
-      end
66  
-    end
67  
-
68  
-    it 'returns string param keys' do
69  
-      with_api(RackRoutes) do
70  
-        get_request({:path => '/hola/bob?foo=key'}, err) do |c|
71  
-          c.response_header.status.should == 200
72  
-          c.response.should == 'hola! {"name"=>"bob", "foo"=>"key"}'
73  
-        end
74  
-      end
75  
-    end
76  
-
77  
-    context 'sinatra style route definition' do
78  
-      it 'should honor the request method' do
79  
-        with_api(RackRoutes) do
80  
-          post_request({:path => '/hello_world'}, err) do |c|
81  
-            c.response_header.status.should == 200
82  
-            c.response.should == 'hello post world!'
83  
-          end
84  
-        end
85  
-      end
86  
-
87  
-      it 'should reject other request methods' do
88  
-        with_api(RackRoutes) do
89  
-          put_request({:path => '/hello_world'}, err) do |c|
90  
-            c.response_header.status.should == 405
91  
-            c.response_header['ALLOW'].split(/, /).should == %w(GET HEAD POST)
92  
-          end
93  
-        end
94  
-      end
95  
-    end
96  
-
97  
-    context 'routes defined with get' do
98  
-      it 'should allow get' do
99  
-        with_api(RackRoutes) do
100  
-          get_request({:path => '/hello_world'}, err) do |c|
101  
-            c.response_header.status.should == 200
102  
-            c.response.should == 'hello world!'
103  
-          end
104  
-        end
105  
-      end
106  
-    end
107  
-
108  
-    context "routes defined with head" do
109  
-      it "should allow head" do
110  
-        with_api(RackRoutes) do
111  
-          head_request({:path => '/hello_world'}, err) do |c|
112  
-            c.response_header.status.should == 200
113  
-          end
114  
-        end
115  
-      end
116  
-    end
117  
-
118  
-    context "defined in blocks" do
119  
-      it "uses middleware defined in the block" do
120  
-        with_api(RackRoutes) do
121  
-          post_request({:path => '/hola/bob'}, err) do |cb|
122  
-            # the /hola route only supports GET requests
123  
-            cb.response_header.status.should == 405
124  
-            cb.response.should == '[:error, "Invalid request method"]'
125  
-            cb.response_header['ALLOW'].should == 'GET'
126  
-          end
127  
-        end
128  
-      end
129  
-
130  
-      it "disallows routing class and run for same route" do
131  
-        with_api(RackRoutes) do
132  
-          get_request({:path => '/bad_route'}, err) do |cb|
133  
-            # it doesn't raise required param error
134  
-            cb.response_header.status.should == 500
135  
-            cb.response.should == "run disallowed: please mount a Goliath API class"
136  
-          end
137  
-        end
138  
-      end
139  
-    end
140  
-
141  
-    context "defined in classes" do
142  
-      it "uses API middleware" do
143  
-        with_api(RackRoutes) do
144  
-          post_request({:path => '/aloha'}, err) do |c|
145  
-            # the /hola route only supports GET requests
146  
-            c.response_header.status.should == 405
147  
-            c.response.should == '[:error, "Invalid request method"]'
148  
-            c.response_header['ALLOW'].should == 'GET'
149  
-          end
150  
-        end
151  
-      end
152  
-    end
153  
-
154  
-    context "with event handlers" do
155  
-      it "collects header events" do
156  
-        with_api(RackRoutes) do
157  
-          get_request({:path => '/headers'}, err) do |c|
158  
-            c.response_header.status.should == 200
159  
-            c.response.should == 'headers: {"Connection"=>"close", "Host"=>"localhost:9900", "User-Agent"=>"EventMachine HttpClient"}'
160  
-          end
161  
-        end
162  
-      end
163  
-
164  
-      it "rejects POST request" do
165  
-        with_api(RackRoutes) do
166  
-          post_request({:path => '/headers'}, err) do |c|
167  
-            # the /headers route only supports GET requests
168  
-            c.response_header.status.should == 405
169  
-            c.response.should == '[:error, "Invalid request method"]'
170  
-            c.response_header['ALLOW'].should == 'GET'
171  
-          end
172  
-        end
173  
-      end
174  
-    end
175  
-  end
176  
-end
32  spec/integration/valid_spec.rb
... ...
@@ -1,6 +1,36 @@
1 1
 require 'spec_helper'
2 2
 require 'json'
3  
-require File.join(File.dirname(__FILE__), '../../', 'examples/valid')
  3
+
  4
+class ValidSingleParam < Goliath::API
  5
+  use Goliath::Rack::Params
  6
+  use Goliath::Rack::Validation::RequiredParam, {:key => 'test'}
  7
+
  8
+  # If you are using Golaith version <=0.9.1 you need to use Goliath::Rack::ValidationError
  9
+  # to prevent the request from remaining open after an error occurs
  10
+  #use Goliath::Rack::ValidationError
  11
+
  12
+  def response(env)
  13
+    [200, {}, 'OK']
  14
+  end
  15
+end
  16
+
  17
+
  18
+class ValidNestedParams < Goliath::API
  19
+  use Goliath::Rack::Params
  20
+
  21
+  # For this validation to pass you need to have this as parameter (json body here)
  22
+  # {
  23
+  #   'data' : {
  24
+  #     'login' : 'my_login'
  25
+  #   }
  26
+  # }
  27
+  #
  28
+  use Goliath::Rack::Validation::RequiredParam, :key => %w(data login)
  29
+
  30
+  def response(env)
  31
+    [200, {}, 'OK']
  32
+  end
  33
+end
4 34
 
5 35
 describe ValidSingleParam do
6 36
   let(:err) { Proc.new { fail "API request failed" } }
8  spec/integration/websocket_spec.rb
@@ -19,24 +19,20 @@ def on_close(env)
19 19
   end
20 20
 end
21 21
 
22  
-class DummyServer < Goliath::API
23  
-  map '/ws', WebSocketEndPoint
24  
-end
25  
-
26 22
 describe "WebSocket" do
27 23
   include Goliath::TestHelper
28 24
 
29 25
   let(:err) { Proc.new { |c| fail "HTTP Request failed #{c.response}" } }
30 26
 
31 27
   it "should accept connection" do
32  
-    with_api(DummyServer, {:verbose => true, :log_stdout => true}) do |server|
  28
+    with_api(WebSocketEndPoint, {:verbose => true, :log_stdout => true}) do |server|
33 29
       WebSocketEndPoint.any_instance.should_receive(:on_open)
34 30
       ws_client_connect('/ws')
35 31
     end
36 32
   end
37 33
 
38 34
   it "should accept traffic" do
39  
-    with_api(DummyServer, {:verbose => true, :log_stdout => true}) do |server|
  35
+    with_api(WebSocketEndPoint, {:verbose => true, :log_stdout => true}) do |server|
40 36
       ws_client_connect('/ws') do |client|
41 37
         client.send "hello"
42 38
         client.receive.should == "hello"
33  spec/unit/api_spec.rb
@@ -9,38 +9,5 @@
9 9
     it "doesn't change after multi calls" do
10 10
       2.times { DummyApi.should have(2).middlewares }
11 11
     end
12  
-
13  
-    it "should include all middlewares from superclasses" do
14  
-      c1 = Class.new(Goliath::API) do
15  
-        use Goliath::Rack::Params
16  
-      end
17  
-
18  
-      c2 = Class.new(c1) do
19  
-        use Goliath::Rack::DefaultMimeType
20  
-      end
21  
-
22  
-      base_middlewares = DummyApi.middlewares
23  
-      middlewares = c2.middlewares - base_middlewares
24  
-
25  
-      middlewares.size.should == 2
26  
-      middlewares[0][0].should == Goliath::Rack::Params
27  
-      middlewares[1][0].should == Goliath::Rack::DefaultMimeType
28  
-    end
29 12
   end
30  
-
31  
-  describe ".maps?" do
32  
-    context "when not using maps" do
33  
-      it "returns false" do
34  
-        DummyApi.maps?.should be_false
35  
-      end
36  
-    end
37  
-
38  
-    context "when using maps" do
39  
-      it "returns true" do
40  
-        DummyApi.map "/foo"
41  
-        DummyApi.maps?.should be_true
42  
-      end
43  
-    end
44  
-  end
45  
-
46 13
 end
40  spec/unit/rack/builder_spec.rb
... ...
@@ -1,40 +0,0 @@
1  
-# encoding: utf-8
2  
-require 'spec_helper'
3  
-
4  
-describe Goliath::Rack::Builder do
5  
-
6  
-  SimpleMiddleware = Class.new
7  
-  NestedMiddleware = Class.new
8  
-
9  
-  class NestedClassApi < Goliath::API
10  
-    use NestedMiddleware, 'class'
11  
-  end
12  
-
13  
-  class NestedBlockApi < Goliath::API
14  
-    use NestedMiddleware, 'block'
15  
-  end
16  
-
17  
-  class SimpleRouter < Goliath::API
18  
-    use SimpleMiddleware
19  
-    map "/class", NestedClassApi
20  
-    map "/block" do
21  
-      run NestedBlockApi.new
22  
-    end
23  
-  end
24  
-
25  
-  let(:router) { SimpleRouter.new }
26  
-
27  
-  describe '.build' do
28  
-
29  
-    it "builds rack app for api" do
30  
-      Rack::Builder.should_receive(:app)
31  
-      Goliath::Rack::Builder.build(router.class, router)
32  
-    end
33  
-
34  
-    it "loads rack/goliath middlewares" do
35  
-      SimpleMiddleware.should_receive(:new)
36  
-      Goliath::Rack::Builder.build(router.class, router)
37  
-    end
38  
-
39  
-  end
40  
-end

0 notes on commit c53d8a4

Please sign in to comment.
Something went wrong with that request. Please try again.