ilusm.dev
Guide

HTTP

Make HTTP requests with net, build HTTP servers with web, and use WebSocket, TCP, and UDP for everything else.

HTTP requests

All HTTP functions return {cod, txt} - cod is the HTTP status code (num), txt is the response body (str).

GET

use net

res = net.get("https://api.example.com/data")
prn res.cod   # 200
prn res.txt   # response body

POST

use net
use jsn

body = jsn.enc({name: "ibot", action: "ping"})
res  = net.post("https://api.example.com/action", body)
prn res.cod

PUT, PATCH, DELETE

res = net.put("https://api.example.com/user/1", body)
res = net.patch("https://api.example.com/user/1", body)
res = net.del("https://api.example.com/user/1")

Request options

To send custom headers with a GET, use net.get_hdr(url, headers_obj):

use net

res = net.get_hdr("https://api.example.com/data", {
    Authorization: "Bearer mytoken",
    Accept: "application/json"
})

For POST/PUT/PATCH, the third argument is the Content-Type string (default is application/json):

# Default content type - application/json
res = net.post("https://api.example.com/action", body)

# Custom content type
res = net.post("https://api.example.com/upload", data, "text/plain")

Building a web server

Use the web module to build an HTTP server with routes:

use web
use jsn

app = web.app()

app.get("/", \(req) "hello from ilusm")

app.get("/ping", \(req)
    web.jsn({ok: tru, msg: "pong"})
)

app.pst("/echo", \(req)
    web.jsn(req.jsn)   # echo back the JSON body
)

app.run(":8080")

Request shape

Every handler receives a req object:

FieldWhat it is
req.mtdHTTP method string ("GET", "POST", …)
req.pthURL path string
req.hdrRequest headers object
req.bodRaw body string
req.qryQuery string parameters object
req.jsnAuto-parsed JSON body (nil if not JSON)

Response helpers

web.jsn({ok: tru})           # JSON 200 response
web.txt("plain text")        # text/plain 200 response
web.red("/other", 302)       # redirect

Custom response

app.get("/status", \(req)
    {cod: 201, bod: "created", hdr: {X-Custom: "yes"}}
)

WebSocket client

use net
use jsn

ws = net.ws("wss://echo.example.com")
ws.snd(jsn.enc({op: "hello"}))
msg = ws.rcv()       # blocks until message
prn msg
ws.cls()

rcv(tmo) accepts an optional timeout in seconds:

msg = ws.rcv(5)   # wait up to 5 seconds, nil on timeout

WebSocket server

use net

srv = net.wss(":8080")
whl tru:
    cli = srv.acc()        # blocks until a client connects
    msg = cli.rcv()
    cli.snd($"echo: {msg}")
srv.cls()

TCP

use net

conn = net.tcp("example.com:9000")
conn.snd("hello\n")
data = conn.rcv()    # up to 64KiB
prn data
conn.cls()

DNS lookup and ping

use net

ips = net.dns("example.com")    # list of IP strings
prn ips[0]

result = net.png("example.com", 5)   # TCP probe, 5s timeout
prn result.ok    # tru/fls
prn result.ms    # round-trip ms