module HTTP

HTTP: require "http". An HTTP/1.1 server for use behind a reverse proxy (docs/11-http.md): a handler takes a Request and returns a Response; the server runs a task per connection.

require "http"
HTTP.serve(8080) { |req| HTTP::Response.text("hello #{req.path}") }

<std:http>:12

Classes and modules

Class methods

def self.reason(status: Int) -> String

The reason phrase of a status ("" for one without).

<std:http>:80

def self.split_target(target: String) -> [String, String]

A request target split at its first ? into the path, percent-decoded, and the query, left as it is ("" when there is none).

A path whose decoding is not UTF-8 is left undecoded.

HTTP.split_target("/a%20b?x=1")   # => ["/a b", "x=1"]
HTTP.split_target("/a")           # => ["/a", ""]

<std:http>:699

def self.percent_decode(s: String, plus: Bool = …) -> String?

Percent-decoding, nil when the result is not UTF-8. plus decodes + as a space (forms and queries).

<std:http>:706

def self.parse_query(q: String) -> Hash[String, Array[String]]

The parameters of the query string q, each name with its values in order.

Names and values are percent-decoded, + as a space (left as they are when the decoding is not UTF-8); a pair without = has the value "", and empty pairs are skipped.

HTTP.parse_query("a=1&b=2&a=3")   # => {"a" => ["1", "3"], "b" => ["2"]}
HTTP.parse_query("a+b=c%20d&&e")  # => {"a b" => ["c d"], "e" => [""]}

<std:http>:748

def self.handler(&f: shareable (HTTP::Request) -> HTTP::Response) -> HTTP::Handler

A handler calling the block (which captures by value).

hello = HTTP.handler { |req| HTTP::Response.text("hello #{req.path}") }
hello.call(HTTP::Request.get("/world")).body
# => HTTP::ResponseBody::Text(text: "hello /world")

<std:http>:1131

def self.serve(port: Int = …, host: String = …, &handler: shareable (HTTP::Request) -> HTTP::Response) -> Void

Serves HTTP on host:port, answering each request with the block's response, until the calling task is cancelled.

A shorthand for HTTP::Server.new with a handler from the block (HTTP.handler) and HTTP::Server#serve.

<std:http>:1773