Http.post
func Http.post(url: string, body: string | Bytes, headers: Map[string, string] = Map{}, timeout: Time.Duration | null = null, ctx: Context | null = null): Result[Http.Response, Error]Http.post sends body to url in a POST request and reads the whole response. It is Http.request with the method "POST".
Details
- A response of any status is
Ok: a 404 or a 500 comes back with itsstatus, and the program checks it.Errmeans there was no response at all, such as no connection, a malformed URL, the timeout, or the context. - No redirect is followed. A 3xx comes back as it is, with its
Locationheader. - The body is sent as given: a string as its UTF-8,
Bytesunchanged. Say what it is with aContent-Typeheader. - The whole response is read before
postreturns, and its body is held once, as received, inbytes; Http.text decodes it.
Basic examples
Start a server on a free local port, then post a string to it with Http.post:
func echo(req: Http.Request): Http.Reply {
Http.Reply{ status: 200, headers: Map{}, body: "${req.method} ${req.path}: ${req.text()}" }
}
let listener = try Net.listen("127.0.0.1:0")
go { _ = Http.serve(listener, echo) }
let res = try Http.post("http://${listener.address()}/notes", "buy milk")
println(res.status)
println(res.text())200
POST /notes: buy milkThe rest of this page posts to url, a local server like the one above. It answers with the method, the path, the Content-Type it got, and the body; /missing answers 404, /moved redirects, /slow takes two seconds, /raw sends the bytes it got back unchanged, and /json sends the body back as JSON.
Name the type of the body with a header:
let res = try Http.post("${url}/notes", "buy milk", headers: Map{ "Content-Type": "text/plain" })
println(res.text())POST /notes (text/plain): buy milkScope
The body is a string or Bytes. An empty string sends an empty body, which /raw sends back:
let text = try Http.post(url, "text")
println(text.text())
let bytes = try Http.post(url, Bytes.fromArray([0x68, 0x69]))
println(bytes.text())
let empty = try Http.post("${url}/raw", "")
println(empty.bytes)POST / (no type): text
POST / (no type): hi
Bytes()Bytes are sent as they are, even when they are not UTF-8. The response keeps them in bytes, while text() has U+FFFD where the text is not valid:
let res = try Http.post("${url}/raw", Bytes.fromArray([0xFF, 0x41]))
println(res.bytes)
println(res.text())Bytes(ff 41)
�AA status that reports a failure is still Ok:
let res = try Http.post("${url}/missing", "x")
println(res.status)
println(res.text())404
no such noteA redirect comes back as it is, and the program decides whether to follow it:
let res = try Http.post("${url}/moved", "x")
println(res.status)
println(res.headers.get("Location"))303
/notes/7Named arguments
Two names that differ only in case name one header, so the call is Err and sends nothing:
println(Http.post("http://127.0.0.1:1/", "x", headers: Map{ "Accept": "text/plain", "accept": "*/*" }))Err{ error: Error{ message: "post \"http://127.0.0.1:1/\": the headers \"Accept\" and \"accept\" differ only in case" } }timeout bounds the whole call, from connecting to the end of the body. When it passes, the result is Err with the message timeout:
println(Http.post("${url}/slow", "x", timeout: 100ms))Err{ error: Error{ message: "timeout" } }ctx bounds the call too, and the result is Err with the context's reason. A context shares one bound across several calls:
let ctx = Context.new(timeout: 100ms)
println(Http.post("${url}/slow", "first", ctx: ctx))
println(Http.post(url, "second", ctx: ctx))Err{ error: Error{ message: "timeout" } }
Err{ error: Error{ message: "timeout" } }When both are given, the earlier bound wins:
let ctx = Context.new(timeout: 10s)
println(Http.post("${url}/slow", "x", timeout: 100ms, ctx: ctx))Err{ error: Error{ message: "timeout" } }A context cancelled by the program gives the reason cancelled:
let ctx = Context.new()
ctx.cancel()
println(Http.post(url, "x", ctx: ctx))Err{ error: Error{ message: "cancelled" } }Applications
Send a record as JSON and read the JSON reply:
type Note = { title: string, done: bool }
let note = Note{ title: "buy milk", done: false }
let headers = Map{ "Content-Type": "application/json" }
let res = try Http.post("${url}/json", Json.stringify(note), headers: headers)
println(res.status)
println(try Json.parse(res.text()))201
Map{ "title": "buy milk", "done": false }Post a form, encoded with Url.stringifyQuery:
let form = Url.stringifyQuery(Map{ "name": ["Ann Lee"], "tag": ["a", "b"] })
let headers = Map{ "Content-Type": "application/x-www-form-urlencoded" }
println((try Http.post("${url}/signup", form, headers: headers)).text())POST /signup (application/x-www-form-urlencoded): name=Ann+Lee&tag=a&tag=bTurn a failing status into an Err, and name the call in every error with Result.wrapErr:
func create(endpoint: string, title: string): Result[string, Error] {
let res = try (Http.post(endpoint, title) | Result.wrapErr("create ${title}"))
if res.status != 200 {
return Result.fail("create ${title}: status ${res.status}")
}
Result.ok(res.text())
}
println(create("${url}/notes", "buy milk"))
println(create("${url}/missing", "call Bob"))Ok{ value: "POST /notes (no type): buy milk" }
Err{ error: Error{ message: "create call Bob: status 404" } }Properties and relations
Http.post is Http.request with the method "POST":
let a = try Http.post("${url}/notes", "x")
let b = try Http.request("POST", "${url}/notes", body: "x")
assert(a.status == b.status)
assert(a.text() == b.text())When the response is UTF-8, text() is its bytes as text:
let res = try Http.post(url, "héllo")
assert(res.text().toBytes() == res.bytes)Possible issues
A zero or negative timeout is Err before anything is sent, as is one with years, months, or weeks, which have no fixed length:
println(Http.post("http://127.0.0.1:1/", "x", timeout: 0s))
println(Http.post("http://127.0.0.1:1/", "x", timeout: Time.duration(weeks: 1)))Err{ error: Error{ message: "post \"http://127.0.0.1:1/\": the timeout is zero or negative" } }
Err{ error: Error{ message: "post \"http://127.0.0.1:1/\": the timeout has years, months or weeks, which have no fixed length" } }try returns early only when there is no response. A 404 is Ok, so check status before using the body:
let res = try Http.post("${url}/missing", "x")
let text = if res.status == 200 { res.text() } else { "failed: ${res.status}" }
println(text)failed: 404A malformed URL is Err:
println(Http.post("http://example.com/%zz", "x"))Err{ error: Error{ message: "post \"http://example.com/%zz\": invalid URL escape \"%zz\"" } }See also
Http.request · Http.get · Http.serve · Http.Response · Json.stringify · Url.stringifyQuery · Context.new
