Kiln / Routes and handlers
Start here01
The language02
- 01The basics
- 02Values and numbers
- 03Variables
- 04Calls and expressions
- 05Conditions and loops
- 06Strings
- 07Arrays and hashes
- 08Classes and records
- 09Traits and enums
- 10Blocks
- 11Methods
- 12Imports and exports
- 13Foreign files
- 14Failures
Programs and the world03
- 01Files, input and output
- 02JSON, time, URLs and random numbers
- 03Html and forms
- 04Templates: Ochre
- 05Built-in methods
Kiln04
04 Kiln / 02
Routes and handlers
Requests go to handlers by their routes, which are checked against the handlers before anything runs.
A request reaches your code through a route, which names the handler that answers it. Kiln checks every route against its handler before anything runs. A path part the handler doesn't take, or a handler that doesn't give a Response, is a mistake found then, so it never turns into a broken page. This page covers handlers, the routes that lead to them, what a request holds, and what happens when a handler fails.
Handlers
A server leads each request to a handler: a method that takes a Request (and the parts of its path, below) and gives a Response. Handlers are usually static methods of a class, one class per part of the site:
import "@kiln"
# What /hello takes: ?name=Ada, or nothing.
record Hello
name: String = "you"
end
class Pages
static def home(request: Request): Response
return Response.html(Html.raw("<h1>Welcome</h1>"), status: 200)
end
static def hello(request: Request): Response!
const hello = try Form.decode(request.query, as: Hello)
return Response.text("Hello, #{hello.name}!", status: 200)
end
endhello reads a name from the query string, with a fallback, so /hello and /hello?name=Ada both get an answer. Requests and responses are the http package's, which Kiln brings in, and templates belong to the language itself.
Routes
A Route says which requests go to which handler. Route.get, post, put, patch and delete each make a route for that HTTP method.
A route names its handler without parentheses. Pages.home is the method itself, while Pages.home(...) would call it:
import "@kiln"
class Pages
static def home(request: Request): Response
return Response.html(Html.raw("<h1>Welcome</h1>"), status: 200)
end
end
const routes = [Route.get("/", to: Pages.home), Route.post("/", to: Pages.home)]
print(routes[1].method) # prints POSTParts of the path
The path is written out, starting with /. A part written :name matches any one part of a request's path, and the handler takes it as a parameter: after the Request, one for each :name, in the path's order, with the same names. Each is an Int or a String.
The type decides what fits. A part the handler takes as an Int fits only a whole number: /users/42 fits /users/:id for show(request: Request, id: Int), but /users/ada doesn't, so that request goes on to the next route, or gets 404.
Kiln holds the handler to all of this, and to giving a Response, when the program is checked: a route that can't work is a mistake where it's written, and the editor shows it as it's typed. When the path and the handler don't agree, the mistake says what the handler should take:
import "@kiln"
class Users
static def show(request: Request, id: Int): Response
return Response.text("user #{id}", status: 200)
end
end
const route = Route.get("/users/:id", to: Users.show)
const wrong = Route.get("/users/:name", to: Users.show) # error: the path '/users/:name' has :name, so Users.show takes (request: Request, name: ...), in that orderRequests
A handler gets the http package's Request:
| Field | Holds |
|---|---|
method: String | "GET", "POST", ... |
path: String | "/users/42", without the query |
query: String | the query as it was sent, without its ?: name=Ada |
headers: {String: String} | names in lowercase |
body: String | the whole body, as text |
files: [Upload] | the files a form sent (see images) |
request.header(name) is a header, by its name in any case. Who sent it is Kiln's to say: Session.of(request) (see accounts), and Htmx.asked(request) (see pages that change in place).
A handler is an ordinary method, so you can try one out by calling it with a Request of your own, with no server running:
import "@kiln"
record Hello
name: String = "you"
end
class Pages
static def hello(request: Request): Response!
const hello = try Form.decode(request.query, as: Hello)
return Response.text("Hello, #{hello.name}!", status: 200)
end
end
const request = new Request(method: "GET", path: "/hello", query: "name=Ada", headers: {}, body: "")
print((try Pages.hello(request)).body) # prints Hello, Ada!A handler reads its query, and a posted form's body, with Form.decode (see forms): into a record of its own, each field typed, with a default where it may be left out. A query that doesn't fit, like page=abc for an Int, fails with kind invalid: 400 Bad request.
Handlers that fail
Handlers often do things that can fail, like finding a row that may not be there. A handler marked ! passes those failures on with try, and the server answers with the status the failure's kind stands for. The message goes into the log; the browser only gets the status's name.
| Failure kind | Status |
|---|---|
ErrorKind.missing | 404 Not found |
ErrorKind.invalid | 400 Bad request |
ErrorKind.denied, ErrorKind.forbidden | 403 Forbidden |
ErrorKind.conflict | 409 Conflict |
| anything else | 500 Internal server error |
Here a user that isn't there is a failure of kind missing, so the browser gets 404:
import "@kiln"
class Users
static def show(request: Request, id: Int): Response!
if id != 1
return failure("there's no user #{id}", kind: ErrorKind.missing)
end
return Response.text("Ada", status: 200)
end
end
const request = new Request(method: "GET", path: "/users/2", query: "", headers: {}, body: "")
Users.show(request, id: 2) rescue error
print(Status.of(error)) # prints 404
endAny other status is a rescue away. Pages of your own for failures, a 404 page or a redirect to sign in, come from one method that Server.start names with failed:: it takes the Request and the Error, and makes the page for every failure, a handler's or a guard's (see guards), and for an address with no page (kind missing).
static def failed(request: Request, error: Error): Response
if error.kind == ErrorKind.denied
return Response.redirect("/sign-in", status: Redirect.see_other)
end
return Response.html(sorry.render(), status: Status.of(error))
end
try Server.start(port: 3000, routes: routes, failed: Pages.failed)- The failure's message still goes into the log.
Status.of(error)is the status from the table above, for the page to answer with the same one.- It can't fail itself: it's what answers a failure.