Browse Source

[ruby/rack] Only set headers not created by servers (#9569)

+------------+------------------------------------+------+-----+-----+------+-------+---------+--------------+
|        name|                         branch_name|  json|   db|query|update|fortune|plaintext|weighted_score|
+------------+------------------------------------+------+-----+-----+------+-------+---------+--------------+
| rack-iodine|                              master|272762|92478|82287| 25252|  76641|   356731|          4319|
| rack-iodine|rack/remove-redundant-content-length|329655|95705|83260| 25488|  80504|   498301|          4458|
+------------+------------------------------------+------+-----+-----+------+-------+---------+--------------+
Petrik de Heus 5 months ago
parent
commit
3c1f93380c
2 changed files with 36 additions and 18 deletions
  1. 0 1
      frameworks/Ruby/agoo/app.rb
  2. 36 17
      frameworks/Ruby/rack/hello_world.rb

+ 0 - 1
frameworks/Ruby/agoo/app.rb

@@ -21,7 +21,6 @@ QUERIES_MIN = 1
 QUERIES_MAX = 500
 
 CONTENT_TYPE = 'Content-Type'
-CONTENT_LENGTH = 'Content-Length'
 DATE = 'Date'
 SERVER = 'Server'
 SERVER_STRING = 'Agoo'

+ 36 - 17
frameworks/Ruby/rack/hello_world.rb

@@ -25,9 +25,7 @@ class HelloWorld
   PLAINTEXT_TYPE = 'text/plain'
   DATE = 'Date'
   SERVER = 'Server'
-  SERVER_STRING = if defined?(PhusionPassenger)
-                    'Passenger'
-                  elsif defined?(Puma)
+  SERVER_STRING = if defined?(Puma)
                     'Puma'
                   elsif defined?(Iodine)
                     'Iodine'
@@ -64,20 +62,6 @@ class HelloWorld
     @db = PgDb.new(DEFAULT_DATABASE_URL, max_connections)
   end
 
-  def respond(content_type, body = '')
-    headers = {
-      CONTENT_TYPE => content_type,
-      DATE => Time.now.utc.httpdate,
-      SERVER => SERVER_STRING
-    }
-    headers[CONTENT_LENGTH] = body.bytesize.to_s if defined?(Unicorn)
-    [
-      200,
-      headers,
-      [body]
-    ]
-  end
-
   def fortunes
     fortunes = @db.select_fortunes
     fortunes << { id: 0, message: 'Additional fortune added at request time.' }
@@ -118,4 +102,39 @@ class HelloWorld
       respond PLAINTEXT_TYPE, 'Hello, World!'
     end
   end
+
+  private
+
+  def respond(content_type, body)
+    [
+      200,
+      headers(content_type, body),
+      [body]
+    ]
+  end
+
+  if defined?(Unicorn)
+    def headers(content_type, body)
+      {
+        CONTENT_TYPE => content_type,
+        SERVER => SERVER_STRING,
+        CONTENT_LENGTH => body.bytesize.to_s
+      }
+    end
+  elsif defined?(Falcon) || defined?(Puma)
+    def headers(content_type, _)
+      {
+        CONTENT_TYPE => content_type,
+        SERVER => SERVER_STRING,
+        DATE => Time.now.utc.httpdate
+      }
+    end
+  else
+    def headers(content_type, _)
+      {
+        CONTENT_TYPE => content_type,
+        SERVER => SERVER_STRING
+      }
+    end
+  end
 end