Module: Syntropy::ResponseMethods

Included in:
Request
Defined in:
lib/syntropy/request/response.rb

Overview

Response methods.

Constant Summary collapse

WEBSOCKET_GUID =
'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'

Instance Method Summary collapse

Instance Method Details

#file_full_path(path, opts) ⇒ String

Returns a fully qualified file path based on the given options.

Parameters:

  • path (String)

    file path

  • opts (Hash)

    options hash

Returns:

  • (String)

    qualified file path



109
110
111
112
113
114
115
# File 'lib/syntropy/request/response.rb', line 109

def file_full_path(path, opts)
  if (base_path = opts[:base_path])
    File.join(opts[:base_path], path)
  else
    path
  end
end

#json_pretty_response(obj, **headers) ⇒ void

This method returns an undefined value.

Renders a nicely-formatted JSON repsonse with JSON content type.

Parameters:

  • obj (any)

    obj to render into JSON

  • headers (Hash)

    additional response headers



257
258
259
260
261
262
263
# File 'lib/syntropy/request/response.rb', line 257

def json_pretty_response(obj, **headers)
  respond(
    JSON.pretty_generate(obj),
    'Content-Type' => 'application/json; charset=utf-8',
    **headers
  )
end

#redirect(url, status = HTTP::FOUND) ⇒ void

This method returns an undefined value.

Responds with a redirect to the given URL. If a relative path is provided as the URL, the absolute URL path will be calculated relative to the current request's path.

Parameters:

  • url (String)

    redirect URL

  • status (Integer) (defaults to: HTTP::FOUND)

    HTTP status code



36
37
38
39
# File 'lib/syntropy/request/response.rb', line 36

def redirect(url, status = HTTP::FOUND)
  url = File.expand_path(File.join(path, url)) if url =~ /^\./
  respond(nil, ':status' => status, 'Location' => url)
end

#redirect_to_host(new_host, status = HTTP::FOUND) ⇒ void

This method returns an undefined value.

Redirect to the same path and query, on a different host.

Parameters:

  • new_host (String)

    new host name

  • status (Integer) (defaults to: HTTP::FOUND)

    HTTP status code



55
56
57
58
# File 'lib/syntropy/request/response.rb', line 55

def redirect_to_host(new_host, status = HTTP::FOUND)
  secure_uri = "//#{new_host}#{uri}"
  redirect(secure_uri, status)
end

#redirect_to_https(status = HTTP::MOVED_PERMANENTLY) ⇒ void

This method returns an undefined value.

Redirects to the same URL, except with HTTPS.

Parameters:

  • status (Integer) (defaults to: HTTP::MOVED_PERMANENTLY)

    HTTP status code



45
46
47
48
# File 'lib/syntropy/request/response.rb', line 45

def redirect_to_https(status = HTTP::MOVED_PERMANENTLY)
  secure_uri = "https://#{host}#{uri}"
  redirect(secure_uri, status)
end

#respond_by_http_method(map) ⇒ void

This method returns an undefined value.

Responds according to the given map. The given map defines the responses for each method. The value for each method is either an array containing the body and header values to use as response, or a proc returning such an array. For example:

req.respond_by_http_method(
  'head'  => [nil, headers],
  'get'   => -> { [IO.read(fn), headers] }
)

If the request's method is not included in the given map, an exception is raised.

Parameters:

  • map (Hash)

    hash mapping HTTP methods to responses



183
184
185
186
187
188
189
190
# File 'lib/syntropy/request/response.rb', line 183

def respond_by_http_method(map)
  value = map[self.method]
  raise Syntropy::Error.method_not_allowed if !value

  value = value.() if value.is_a?(Proc)
  (body, headers) = value
  respond(body, headers)
end

#respond_html(html, **headers) ⇒ void

This method returns an undefined value.

Renders an HTML repsonse with HTML content type.

Parameters:

  • html (String)

    HTML response body

  • headers (Hash)

    additional response headers



231
232
233
234
235
236
237
# File 'lib/syntropy/request/response.rb', line 231

def respond_html(html, **headers)
  respond(
    html,
    'Content-Type' => 'text/html; charset=utf-8',
    **headers
  )
end

#respond_json(obj, **headers) ⇒ void

This method returns an undefined value.

Renders a JSON repsonse with JSON content type.

Parameters:

  • obj (any)

    obj to render into JSON

  • headers (Hash)

    additional response headers



244
245
246
247
248
249
250
# File 'lib/syntropy/request/response.rb', line 244

def respond_json(obj, **headers)
  respond(
    JSON.dump(obj),
    'Content-Type' => 'application/json; charset=utf-8',
    **headers
  )
end

#respond_on_get(body, headers = {}) ⇒ void

This method returns an undefined value.

Responds to GET requests with the given body and headers. Otherwise raises an exception.

Parameters:

  • body (String, nil)

    response body

  • headers (Hash) (defaults to: {})

    response headers



198
199
200
201
202
203
204
205
206
207
# File 'lib/syntropy/request/response.rb', line 198

def respond_on_get(body, headers = {})
  case self.method
  when 'head'
    respond(nil, headers)
  when 'get'
    respond(body, headers)
  else
    raise Syntropy::Error.method_not_allowed
  end
end

#respond_on_post(body, headers = {}) ⇒ void

This method returns an undefined value.

Responds to POST requests with the given body and headers. Otherwise raises an exception.

Parameters:

  • body (String, nil)

    response body

  • headers (Hash) (defaults to: {})

    response headers



215
216
217
218
219
220
221
222
223
224
# File 'lib/syntropy/request/response.rb', line 215

def respond_on_post(body, headers = {})
  case self.method
  when 'head'
    respond(nil, headers)
  when 'post'
    respond(body, headers)
  else
  raise Syntropy::Error.method_not_allowed
  end
end

#respond_with_static_file(path, etag, last_modified, opts) ⇒ void

This method returns an undefined value.

Renders a static file response.

Parameters:

  • path (String)

    file path

  • etag (String)

    ETag

  • last_modified (String)

    last-modified value

  • opts (Hash)

    options



124
125
126
127
128
129
130
131
# File 'lib/syntropy/request/response.rb', line 124

def respond_with_static_file(path, etag, last_modified, opts)
  cache_headers = (etag || last_modified) ? {
    'etag' => etag,
    'last-modified' => last_modified
  } : {}

  adapter.respond_with_static_file(self, path, opts, cache_headers)
end

#serve_file(path, opts = {}) ⇒ void

This method returns an undefined value.

Serves a static file as a response, with cache headers.

Parameters:

  • path (String)

    file path

  • opts (Hash) (defaults to: {})

    options



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/syntropy/request/response.rb', line 65

def serve_file(path, opts = {})
  full_path = file_full_path(path, opts)
  stat = File.stat(full_path)
  etag = StaticFileCaching.file_stat_to_etag(stat)
  last_modified = StaticFileCaching.file_stat_to_last_modified(stat)

  if validate_static_file_cache(etag, last_modified)
    return respond(nil, {
      ':status' => HTTP::NOT_MODIFIED,
      'etag' => etag
    })
  end

  mime_type = MimeTypes[File.extname(path)]
  opts[:stat] = stat
  (opts[:headers] ||= {})['Content-Type'] ||= mime_type if mime_type

  respond_with_static_file(full_path, etag, last_modified, opts)
rescue Errno::ENOENT
  respond(nil, ':status' => HTTP::NOT_FOUND)
end

This method returns an undefined value.

Sets a response cookie.

Parameters:

  • key (String)

    cookie name

  • value (String)

    cookie value



146
147
148
# File 'lib/syntropy/request/response.rb', line 146

def set_cookie(key, value)
  adapter.set_cookie(key, value)
end

#set_response_headers(headers) ⇒ void

This method returns an undefined value.

Set additional response headers.

Parameters:

  • headers (Hash)

    response headers



137
138
139
# File 'lib/syntropy/request/response.rb', line 137

def set_response_headers(headers)
  adapter.set_response_headers(headers)
end

#upgrade(protocol, custom_headers = nil, &block) ⇒ void

This method returns an undefined value.

Upgrades the connection to the given protocol, yielding the connection to the given block.

Parameters:

  • protocol (String)

    upgraded protocol

  • custom_headers (Hash, nil) (defaults to: nil)

    additional response headers



156
157
158
159
160
161
162
163
164
165
166
# File 'lib/syntropy/request/response.rb', line 156

def upgrade(protocol, custom_headers = nil, &block)
  upgrade_headers = {
    ':status' => HTTP::SWITCHING_PROTOCOLS,
    'Upgrade' => protocol,
    'Connection' => 'upgrade'
  }
  upgrade_headers.merge!(custom_headers) if custom_headers

  respond(nil, upgrade_headers)
  adapter.with_stream(&block)
end

#upgrade_to_websocket(custom_headers = nil) ⇒ void

This method returns an undefined value.

Upgrades a request to the WebSocket protocol.

Parameters:

  • custom_headers (Hash, nil) (defaults to: nil)

    additional response headers



18
19
20
21
22
23
24
25
26
27
# File 'lib/syntropy/request/response.rb', line 18

def upgrade_to_websocket(custom_headers = nil)
  key = "#{headers['sec-websocket-key']}#{WEBSOCKET_GUID}"
  upgrade_headers = {
    'Sec-WebSocket-Accept' => Digest::SHA1.base64digest(key)
  }
  upgrade_headers.merge!(custom_headers) if custom_headers
  upgrade('websocket', upgrade_headers)

  adapter.websocket_connection(self)
end

#validate_static_file_cache(etag, last_modified) ⇒ bool

Validates a static file cache against the request cache headers. Returns true if cache headers are valid.

Parameters:

  • etag (String)

    ETag

  • last_modified (String)

    last-modified value

Returns:

  • (bool)

    are cache headers valid



93
94
95
96
97
98
99
100
101
102
# File 'lib/syntropy/request/response.rb', line 93

def validate_static_file_cache(etag, last_modified)
  if (none_match = headers['if-none-match'])
    return true if none_match == etag
  end
  if (modified_since = headers['if-modified-since'])
    return true if modified_since == last_modified
  end

  false
end