Skip to content
📌 OpenRun 1.0 is released, read the announcement

Routing

OpenRun routes requests with the chi routing library. An app declares its routes in the routes array of ace.app. There are three route types:

RouteFunctionResponse
HTMLace.htmlA page, with optional fragments for partial HTMX updates
APIace.apiJSON (default) or plain text
Proxyace.proxyForwarded to another service

HTML routing is built for hypermedia exchange: routes are defined in terms of pages and fragments within the pages. This makes it clear which API does what and gives an easy way to deal with partial HTMX driven requests and full page refreshes. A simple application might have one page with some interactions within it. Larger applications are composed of multiple pages, each with some interactive fragments.

Routes

The app contains a routes array, which defines all the routes for the app. For example, the app definition

app.star
app = ace.app("hello1",
              routes = [
                 ace.html("/"),
                 ace.html("/help", "help.go.html")
              ]
             )

defines two routes. / routes to the default index page, /help routes to the help page. Routes can be of three types: HTML, API and Proxy.

HTML Route

An HTML route defined using ace.html defines the properties for an HTML page. The response is HTML text. The data returned by the handler function is passed to the template. If the handler returns an ace.response or ace.redirect, then that takes effect, otherwise the template is rendered.

An HTML route can have fragments defined within it. These are sub-APIs used for hypermedia driven interactions from the main page.

The parameters for ace.html are:

PropertyOptionalTypeDefaultNotes
pathFalsestringThe route, should start with a /
fullTruestringindex.go.html if custom layout, else index_gen.go.htmlThe template to use for full page requests
partialTruestringNoneThe template to use for partial page requests
handlerTruefunctionhandler (if defined)The handler function to use for the route
fragmentsTrueace.fragment[][]The fragment array
methodTruestringGETThe HTTP method type: GET,POST,PUT,DELETE etc, for example ace.GET

Fragment

The fragments array in the html page definition defines the API interactions within the page. The parameters for ace.fragment are:

PropertyOptionalTypeDefaultNotes
pathFalsestringThe route, should not start with a /
partialTruestringInherited from pageThe template to use for partial requests
handlerTruefunctionInherited from pageThe handler function to use for the route
methodTruestringGETThe HTTP method type: GET,POST,PUT,DELETE etc, for example ace.GET
partial and handler are inherited from the page level, unless overridden for the fragment.

A fragment with an empty path ("") registers on the page path itself, defining a method variant of the page. This expresses a form page’s POST without repeating the page’s template:

app.star
ace.html("/items/create", full="item_form.go.html", handler=create_page_handler,
    fragments=[
        ace.fragment("", method=ace.POST, handler=create_submit_handler),
    ]
)

For example, in this page definition

app.star
ace.html("/game/{game_id}", full="game.go.html", partial="game_info_tmpl", handler=game_handler,
    fragments=[
        ace.fragment(
            "submit", method=ace.POST, handler=lambda req: post_game_update(req, "submit")),
        ace.fragment(
            "refresh", partial="refresh_tmpl")
    ]
)

there are three APIs defined:

APIHandlerFull page responsePartial (HTMX) response
GET /game/{game_id}game_handlergame.go.htmlgame_info_tmpl template
POST /game/{game_id}/submitThe lambda functiongame_info_tmpl template, inherited from the page
GET /game/{game_id}/refreshgame_handler, inherited from the pagegame.go.htmlrefresh_tmpl template

API Route

An API route defines a route which returns JSON (default) or plain text response. The handler response is converted to the desired format and returned. The parameters for ace.api are:

PropertyOptionalTypeDefaultNotes
pathFalsestringThe route, should start with a /
handlerTruefunctionhandler (if defined)The handler function to use for the route
methodTruestringGETThe HTTP method type: GET,POST,PUT,DELETE etc, for example ace.GET
typeTruestringJSONThe response type, ace.JSON or ace.TEXT

For example

app.star

def handler(req):
    return {"a": 1}

app = ace.app("api",
              routes = [
                 ace.api("/myapi")
              ]
             )

A GET request to /myapi endpoint will return JSON {"a": 1}.

Proxy Route

A Proxy route defines a route which has to be proxied to another service. All API calls under that route are proxied (all methods and all sub-routes). Websocket connections are also proxied. Proxy uses a plugin based config, the app has to be authorized to do the proxying. The parameters for ace.proxy are:

PropertyOptionalTypeDefaultNotes
pathFalsestringThe route, should start with a /
configFalseProxyConfigThe proxy configuration to use

The proxy configuration proxy.config has the options:

PropertyOptionalTypeDefaultNotes
urlFalsestringThe url to forward the requests to
strip_pathTruestringAdditional path components to strip from the request path. The app installation path is always stripped.
preserve_hostTruebooleanfalseWhether to preserve the Host header. Default false, the Host header is set to the target host value
strip_appTruebooleantrueWhether to strip the app installation path from the proxied request path. Default true
response_headersTruedict{}Headers to set on the proxied response, header name to string value. $url in a value is replaced with the request path

For example, an app which forwards requests to www.google.com is

app.star
load("proxy.in", "proxy")

app = ace.app("Proxy",
              routes=[
                ace.proxy("/", proxy.config("https://www.google.com")),
              ],
              permissions=[
                  ace.permission("proxy.in", "config", ["https://www.google.com"]),
              ],
      )

The plugin is authorized to allow proxying to https://www.google.com. Any request to the app is forwarded after stripping the app path. With the app installed at /test:

ConfigRequestForwarded as
Default/test/abc/def/abc/def
strip_path="/abc"/test/abc/def/def
strip_app=False/test/abc/def/test/abc/def (the app path is kept)
  • Static files: if proxying is enabled for the / route, /static file serving is disabled for the app since requests to the static path are also forwarded to the upstream service. /static_root serving is available and overrides the proxy config.
  • Forwarding headers: OpenRun sanitizes forwarding headers before proxying. Inbound Forwarded and X-Forwarded-* / X-Real-IP headers are not passed through as-is. OpenRun computes the client IP using security.trusted_proxies and sends a clean forwarding header set to the upstream service.

See proxy plugin for details about the proxy config.

Note: If the upstream service uses relative paths, then all requests are automatically proxied. If the service uses absolute paths, then it is better that the app is installed at the root path, like example.com: instead of example.com:/test. If the service uses absolute paths including the domain name, then the client will see the absolute paths and those requests will not come through the proxy. The HTML body is not rewritten by OpenRun to rewrite path references. The upstream service needs to use relative paths to ensure that all requests come through OpenRun.

Request Flow

The API flow is

  • The API is first sent to the matching app
  • Within the app, the API is routed based on the routes defined
  • If there is a handler defined for the matched route, the handler function is called with the request as argument
  • The response template is invoked, with an input map containing a Data property as returned by the handler function
  • If the API type is set to JSON, the handler response is directly returned, with no template being used
  • If automatic error handling is enabled (error_handler is defined), then the error handler function is called if there is an error during the handler invocation. The error handler does the response processing, the templates defined in the route are not used.

Notes

  • For HTMX requests, the partial template is used. For regular requests, the page-level full template is used
  • With structured templates (a base_templates folder is present), full normally names a template file. It can instead name a {{define}} block from the base templates, which is useful for endpoints whose response is only a fragment (for example an HTMX component update), so no dedicated template file is needed. Template names passed to ace.response resolve the same way
  • If there is a function called handler defined, that is the default handler function for all APIs
  • For non-HTMX update requests (POST/PUT/DELETE), the Post-Redirect-Get pattern is automatically implemented by redirecting to the location pointed to by the Referer header.