Module: HTTPTools::Builder

Defined in:
lib/http_tools/builder.rb

Overview

HTTPTools::Builder is a provides a simple interface to build HTTP requests & responses. It can be used as a mixin or class methods on HTTPTools::Builder.

Constant Summary collapse

KEY_VALUE =
"%s: %s\r\n".freeze

Class Method Summary collapse

Class Method Details

.format_headers(headers) ⇒ Object



40
41
42
# File 'lib/http_tools/builder.rb', line 40

def format_headers(headers)
  headers.inject("") {|buffer, kv| buffer << KEY_VALUE % kv}
end

.request(method, host, path = "/", headers = {}) ⇒ Object

:call-seq: Builder.request(method, host, path=“/”, headers={}) -> string

Returns a HTTP request line and headers.

Builder.request(:get, "example.com")\

> “GET / HTTP/1.1rnHost: example.comrnrn”

Builder.request(:post, "example.com", "/form", "Accept" => "text/html")\

> “POST” /form HTTP/1.1rnHost: example.comrnAccept: text/htmlrnrn“



35
36
37
38
# File 'lib/http_tools/builder.rb', line 35

def request(method, host, path="/", headers={})
  "#{method.to_s.upcase} #{path} HTTP/1.1\r\nHost: #{host}\r\n#{
    format_headers(headers)}\r\n"
end

.response(status, headers = {}) ⇒ Object

:call-seq: Builder.response(status, headers={}) -> string

Returns a HTTP status line and headers. Status can be a HTTP status code as an integer, or a HTTP status message as a lowercase, underscored symbol.

Builder.response(200, "Content-Type" => "text/html")\

> “HTTP/1.1 200 okrnContent-Type: text/htmlrnrn”

Builder.response(:internal_server_error)\

> “HTTP/1.1 500 Internal Server Errorrnrn”



22
23
24
# File 'lib/http_tools/builder.rb', line 22

def response(status, headers={})
  "HTTP/1.1 #{STATUS_LINES[status]}\r\n#{format_headers(headers)}\r\n"
end