Http.text
func Http.text(r: Http.Response | Http.Request): stringHttp.text returns the body of r decoded as UTF-8, with bytes that are not valid UTF-8 as U+FFFD, as all text from outside is. It decodes on every call, so a program that needs the text twice binds it once.
Details
Http.textdecodes the body as UTF-8 whatever theContent-Typeheader says. Each malformed sequence becomes U+FFFD, soHttp.textnever fails, and the bytes it replaced cannot be recovered from the text.byteskeeps the body as received.- A byte order mark at the start of the body is kept, as U+FEFF.
Basic examples
Get a page from a local server and decode its body:
let listener = try Net.listen("127.0.0.1:0")
go { _ = Http.serve(listener, { Http.Reply{ status: 200, headers: Map{}, body: "Hello, ${x.path}" } }) }
let response = try Http.get("http://${Net.address(listener)}/world")
println(Http.text(response))Hello, /worldIn a handler, Http.text decodes the body of the request:
func handle(req: Http.Request): Http.Reply {
Http.Reply{ status: 200, headers: Map{}, body: Http.text(req).toUpper() }
}
let listener = try Net.listen("127.0.0.1:0")
go { _ = Http.serve(listener, handle) }
let response = try Http.post("http://${Net.address(listener)}/shout", "hello")
println(response.text())HELLOScope
A response or a request
Http.text takes an Http.Response or an Http.Request. A record built by hand decodes like one that arrived, which shows what the decoding does without a server:
let none: Map[string, string] = Map{}
let response = Http.Response{ status: 200, headers: none, bytes: "héllo".toBytes() }
let request = Http.Request{
method: "POST",
path: "/",
query: "",
headers: none,
bytes: "a=1".toBytes(),
remote: "127.0.0.1:5000",
}
println(Http.text(response))
println(Http.text(request))héllo
a=1Bytes that are not UTF-8
Each malformed sequence becomes U+FFFD. The bytes FF FE are two such sequences, and E2 82, a euro sign cut short, is one:
let none: Map[string, string] = Map{}
let broken = Http.Response{ status: 200, headers: none, bytes: Bytes.fromArray([0xFF, 0xFE, 0x68, 0x69]) }
let cut = Http.Response{ status: 200, headers: none, bytes: Bytes.fromArray([0x31, 0xE2, 0x82]) }
println(broken.text() == "\u{FFFD}\u{FFFD}hi")
println(cut.text() == "1\u{FFFD}")true
trueA byte order mark
A byte order mark at the start stays in the text. Remove it with String.trimPrefix:
let none: Map[string, string] = Map{}
let marked = Http.Response{ status: 200, headers: none, bytes: Bytes.fromArray([0xEF, 0xBB, 0xBF, 0x68, 0x69]) }
let text = marked.text()
println(text.length())
println(text.trimPrefix("\u{FEFF}"))3
hiAn empty body
A response without a body decodes to "". Here /empty answers 204:
let response = try Http.get("${base}/empty")
println(response.status)
println(response.text() == "")204
trueAs a function value
Http.text is a function value like any other, so it can be passed to Result.map. Here /hello answers Hello, Ant:
println(Http.get("${base}/hello").map(Http.text))Ok{ value: "Hello, Ant" }Applications
Parse a JSON response
Decode the body, then parse it with Json.parse. Here /user answers {"name": "Ann", "age": 31}:
let response = try Http.get("${base}/user")
let user = try Json.parse(response.text())
println(user)Map{ "name": "Ann", "age": 31.0 }Read a body line by line
Here /todo answers three lines:
let response = try Http.get("${base}/todo")
for item in response.text().lines() {
println("- ${item}")
}- milk
- eggs
- breadRead a form in a handler
A form posted as application/x-www-form-urlencoded has the same shape as a query string, so Url.parseQuery reads the decoded body:
func handle(req: Http.Request): Http.Reply {
let none: Map[string, string] = Map{}
let form = Url.parseQuery(req.text())
if form is Err { return Http.Reply{ status: 400, headers: none, body: form.error.message } }
let name = form.value.get("name")?.first() ?? "stranger"
Http.Reply{ status: 200, headers: none, body: "Hello, ${name}" }
}
let listener = try Net.listen("127.0.0.1:0")
go { _ = Http.serve(listener, handle) }
let base = "http://${Net.address(listener)}"
let form = Map{ "Content-Type": "application/x-www-form-urlencoded" }
println((try Http.post("${base}/greet", "name=Ann+Lee", headers: form)).text())
println((try Http.post("${base}/greet", "", headers: form)).text())Hello, Ann Lee
Hello, strangerTell text from binary
String.fromBytes is null when the bytes are not UTF-8, which Http.text cannot tell you. Here /hello answers text and /logo the four bytes a PNG file starts with:
for path in ["/hello", "/logo"] {
let response = try Http.get("${base}${path}")
let text = String.fromBytes(response.bytes)
println(if text == null { "${path}: binary" } else { "${path}: text" })
}/hello: text
/logo: binaryProperties and relations
Http.text decodes bytes as String.fromBytesLossy does. For a body that is UTF-8, encoding the text gives the bytes back:
let none: Map[string, string] = Map{}
let response = Http.Response{ status: 200, headers: none, bytes: "naïve café".toBytes() }
assert(Http.text(response) == String.fromBytesLossy(response.bytes))
assert(response.text().toBytes() == response.bytes)
assert(response.text() == String.fromBytes(response.bytes))Possible issues
The text loses bytes that are not UTF-8
Each malformed sequence becomes the three bytes of U+FFFD, so the text of a binary body does not encode back to the body. Use bytes for an image, or for a signature computed over what was sent. Here /logo answers the four bytes a PNG file starts with:
let response = try Http.get("${base}/logo")
println(response.bytes)
println(response.text().toBytes())Bytes(89 50 4e 47)
Bytes(ef bf bd 50 4e 47)The charset in Content-Type is not used
A body in another encoding decodes as UTF-8 all the same. Here /latin1 answers café in ISO-8859-1, where é is the single byte E9, which is not UTF-8:
let response = try Http.get("${base}/latin1")
println(response.headers["Content-Type"])
println(response.text() == "caf\u{FFFD}")text/plain; charset=iso-8859-1
trueA reply has no text
Http.text takes what arrives, not what a handler sends. An Http.Reply holds its body in body, already a string or Bytes:
let reply = Http.Reply{ status: 200, headers: Map{}, body: "hi" }
println(Http.text(reply)) // error: cannot use Http.Reply where Http.Response | Http.Request is expectedDecoding twice
Each call decodes the whole body again. Bind the text once and use the name:
let response = try Http.get("${base}/todo")
let text = response.text()
println(text.lines().length())
println(text.count("e"))3
2See also
Http.Response · Http.Request · Http.get · Http.serve · String.fromBytesLossy · String.fromBytes · Bytes
