HTTP Module
Import using: use http
Note: The HTTP module uses plain TCP and does not currently support HTTPS (SSL/TLS). Use
http:// URLs only.HTTP Client
http.get(url)- HTTP GET request.http.post(url, body?, headers?)- HTTP POST request.http.put(url, body?, headers?)- HTTP PUT request.http.del(url, headers?)- HTTP DELETE request.http.patch(url, body?, headers?)- HTTP PATCH request.http.head(url)- HTTP HEAD request.http.options(url)- HTTP OPTIONS request.http.request(method, url, body?, headers?)- Generic HTTP request.
All client methods return a Map with keys: statusCode, statusText, httpVersion, headers, body. Returns Null on any connection or protocol error.
use http
# GET request
let res = http.get("http://httpbin.org/get")
print("Status: " + str(res["statusCode"]))
# POST with body
let postRes = http.post("http://httpbin.org/post",
'{"data": "hello"}',
{"Content-Type": "application/json"})
print("POST statusCode: " + str(postRes["statusCode"]))
print(postRes["body"])
# Request with custom method
let custom = http.request("PATCH",
"http://httpbin.org/patch",
'{"patch": true}')
print("PATCH statusCode: " + str(custom["statusCode"]))
HTTP Server
http.createServer(handler)- Create HTTP server. Handler receivesfn(req, res)with request object and response object.
Server instance methods: server.listen(port), server.close().
Request properties: req.method, req.path, req.body, req.headers (Map). Methods: req.isMethod(name), req.header(name), req.toString().
Response methods: res.send(body), res.sendStatus(code), res.sendJson(obj), res.redirect(path), res.status(code, text), res.setHeader(name, value).
use http
let srv = http.createServer(fn(req, res)
if req.path == "/hello"
res.send("Hello from Djazair")
elif req.path == "/json"
res.sendJson({"name": "Djazair", "type": "language"})
elif req.path == "/status"
res.sendStatus(404)
elif req.path == "/redirect"
res.redirect("/hello")
else
res.send("OK")
end
end)
srv.listen(8080)
# srv.close() to stop
Classes & Helpers
http.httpParser- HTTP protocol parser. Methods:split(raw),parseHeaders(lines),parseRequest(raw),parseResponse(raw).http.httpResponseBuilder- Builder for constructing raw HTTP responses. Methods:status(code, text),setHeader(name, value),build(body),buildStatus(code),buildJson(obj),buildRedirect(path).http.STATUS_TEXTS- Map of HTTP status codes to reason phrases.http.statusText(code)- Get status text for a status code.
use http
# Get status text
print(http.statusText(200)) # OK
print(http.statusText(404)) # Not Found
print(http.statusText(500)) # Internal Server Error