Net

network-related functions and helpers


Functions


The Net module provides functionality for network operations, including HTTP requests, file downloads, mail sending, and web serving capabilities.

Key Concepts

  • HTTP requests (GET, POST, PUT, PATCH, DELETE)
  • File downloads
  • Email sending
  • Web server functionality
  • Browser integration

Basic Usage

HTTP Requests

; basic GET request
response: request "https://api.example.com/data" ø
print response\body

; POST with JSON data
data: #[name: "John" age: 30]
response: request.post.json "https://api.example.com/users" data

; custom headers
response: request "https://api.example.com/data" .headers: #[
    authorization: "Bearer abc123"
    accept: "application/json"
] ø

; other HTTP methods
response: request.put "https://api.example.com/users/1" data
response: request.patch "https://api.example.com/users/1" data
response: request.delete "https://api.example.com/users/1" ø

Important
When making HTTP requests, always handle potential network errors and timeouts appropriately.

File Downloads

; download file
download "https://example.com/file.pdf"

; download with custom filename
download.as:"local.pdf" "https://example.com/file.pdf"

Sending Emails

; basic email
mail "recipient@email.com" "Hello!" "This is the message body"

; with custom SMTP configuration
mail .using: #[
        server: "smtp.company.com"
        port: 587
        username: "sender@company.com"
        password: "secret"
] "recipient@email.com" "Meeting reminder" "Don't forget our meeting tomorrow!" 

Opening URLs

; open URL in default browser
browse "https://arturo-lang.io"

Common Patterns

Simple REST API Client

define :apiClient [
    init: constructor [baseUrl token]

    headers: method [][
        #[
            authorization: join ["Bearer " \token]
            "content-type": "application/json"
        ]
    ]

    get: method.distinct [endpoint][
        request join @[\baseUrl endpoint] .headers: \headers ø
    ]

    post: method [endpoint data][
        request.post.json join @[\baseUrl endpoint] .headers: \headers data
    ]
]

; create a new API Client
apiClient: to :apiClient ["https://api.example.com" ""]!

; usage
response: apiClient\get "/users"
newUser: apiClient\post "/users" #[name: "John" email: "john@email.com"]

Mini Web Server

; create a simple web server
serve [
    GET "/" [
        render.template {
            <html>
                <body>
                    <h1>Welcome!</h1>
                    <p>The time is: <||= now ||></p>
                </body>
            </html>
        }
    ]

    ; regex routes: named capture groups
    ; become the action's parameters
    GET {//post/(?<id>[0-9]+)/} $[id][
        render.template {
            This is post with id: <||= id ||>
        }
    ]

    ; serve static files - only allow plain filenames,
    ; never pass the raw path to `read`!
    GET {//css/(?<file>[a-zA-Z0-9_-]+\.css)/} $[file][
        path: ~"css/|file|"
        if not? file? path ->
            return emit.status: 404 "Not found"

        emit.css read path
    ]
]

Routes can also take path parameters, Sinatra-style: :name matches a single path segment, * matches anything (slashes included). Routes are tried top to bottom, and any catches whatever didn't match:

serve [
    ; literal routes first: this one wins over `/users/:id`
    GET "/users/new"            -> "New user form"

    ; `:name` params are matched by name...
    GET "/users/:id"            $[id][ ~"User #|id|" ]
    GET "/users/:id/posts/:pid" $[pid, id][ ~"Post #|pid| by user #|id|" ]

    ; ...while `*` ones fill the remaining params, in order
    GET "/say/*/to/*"           $[what, who][ ~"|what|, |who|!" ]

    ; path params, query string & request body - all together
    POST "/users/:id"           $[id, name][
        emit.json write.json #[ id: id name: name updated: true ] ø
    ]

    ; fallback, if nothing else matched
    GET any                     -> "Nothing here!"
]

; $> curl localhost:18966/users/42/posts/7
; Post #7 by user #42

; $> curl localhost:18966/say/hello/to/world
; hello, world!

; $> curl -X POST localhost:18966/users/42 -d "name=John"
; {
;     "id": "42",
;     "name": "John",
;     "updated": true
; }

Tip
The serve function can also open Chrome in app mode with .chrome for a more app-like experience.

Asynchronous Operations

Every network operation here has an .async flavour. Instead of blocking, it returns a :task you can wait on later - letting you fire off several requests at once and collect them when ready:

; a single non-blocking request
t: request.async "https://example.com" ø
response: wait t
print response\status

; many in flight at once, collected in input order
urls: ["https://a.com" "https://b.com" "https://c.com"]
pages: wait.all map urls 'u -> request.async u ø

.async is available across the module:

t: request.async "https://example.com" ø                    ; HTTP request
t: download.async "https://example.com/big.zip" .as:"big.zip"
t: mail.async "x@y.com" "hi" "hello"
s: serve.async.silent.port: 8000 [ GET "/" -> "ok" ]

A .async server keeps running in the background; cancel it to close the socket and free the port:

s: serve.async.silent.port: 8000 [ GET "/" -> "ok" ]
; ... do other work ...
cancel s

Tip
You don't even need .async to get concurrency inside a parallel iterator - plain request / download automatically yield cooperatively when run on a non-main fiber. So map.parallel urls 'u -> request u ø already overlaps its requests. See the Tasks and Iterators modules.