Ink by Example — HTTP

Ink by Example: HTTP

Ink can both send and receive HTTP requests.

std := load('../vendor/std')
log := std.log


We can initiate an HTTP request with req. It returns a function that aborts the request. Let's also time this request.

t := time()
data := {
    method: 'GET'
    url: 'https://example.org'
    headers: {}
    body: ''
}

close := req(data, evt => evt.type :: {
    ` this matches during a request fail 
      or if the request is aborted `
    'error' -> log('Error: ' + evt.message)
    _ -> (
        log('Req: ')
        elasped := string(time() - t)
        log('  elapsed time: ' + elasped)
        log('  ' + string(keys(evt.data)))
    )
})
log('This code runs while we request.')
`` close() would abort the request


A HTTP web server can be started with listen. Similar to req, it returns a function that stops the server.

resp := {
    status: 200
    headers: {'Content-Type': 'text/plain'}
    body: 'Hello from Ink land!'
}
close := listen('0.0.0.0:80', evt => evt.type :: {
    'error' -> log('Error: ' + evt.message)
    'req' -> (evt.end)(resp)
})
log('This code runs while we listen.')

` stop the server `
close()

listen errors in this project's deploy pipeline due to permissions but will work locally.

$ ink http.ink
This code runs while we request.
This code runs while we listen.
Error: error starting http server in listen(), listen tcp 0.0.0.0:80: bind: permission denied
Req: 
  elapsed time: 0.12629604
  {0: 'status', 1: 'headers', 2: 'body'}

Next example: Random.