Your first BSX page
We’ll build a page you can open at localhost:8080. All it needs is a heading and a function to send that heading to the browser.
What the server needs
Let’s call our function hello. For now it can return the same page for every request. Once you have two pages, you’ll want a router to choose a different function for each address.
1. Add Hello.bsx
In the checkout, find main.bend. Create a file called Hello.bsx in that same directory and copy the example below into it. If you put it in a subdirectory, its relative imports will point to the wrong place.
import Base
import ./libs/http/Text.bend as Text
import ./libs/http/Http.bend as Http
import ./libs/html/Html.bend as Html
import ./src/Bwf/Server.bend as Server
def welcome() -> Html.Html:
<h1>Hello, Bend!</h1>
def hello(request: Http.Request) -> IO(Http.Response):
IO.pure(Http.Response, Http.html(200, Html.render(welcome())))
def main() -> IO(Unit):
Server.serve(~hello, "127.0.0.1", 8080)2. Build the app and open the page
Install the build tools and run npm ci in the Bwf checkout. Run these commands from the same directory. The second command leaves the server running in the terminal.
./scripts/bwf build --target js --entry Hello.bsx --output build/hello.js &&
bun build/hello.js
Open http://127.0.0.1:8080/. You should see Hello, Bend! in the browser. In a separate terminal, run curl -i http://127.0.0.1:8080/. Look for status 200 at the top and the heading tag after the response headers.
3. Follow the HTML through the handler
Start at welcome(). The markup gives you an Html.Html value. In hello, Html.render turns that value into a string. Http.html uses it as the response body and supplies the HTML content type. In main, ~hello passes the server a closed template for handling requests.
Here is the line where the response becomes an HTTP value.
def hello(request: Http.Request) -> IO(Http.Response):
IO.pure(Http.Response, Http.html(200, Html.render(welcome())))4. Try a second path
Run curl -i http://127.0.0.1:8080/example. It returns the same heading because the handler always builds the same response.
The Journal needs a different action for each operation. It uses an OpenAPI contract to route requests by method and path.
Open examples/canonical/RouteBindings.bend and find localized_app. The Journal mounts the handlers and supplies a localized layout, a form field error renderer, and the error views.
Router.dispatch_with_form_theme(~Config.field_error, body => Layout.default_layout(locale, body),
Errors.views(), Api.mount(~handler), config, request)