You will use
whiplashto start the listenerpooka/httpfor request and response typespooka/otpto keep the entry point alivepooka/httpcto send real requests from a test
The whole program
module main
import pooka/http
import pooka/otp
import whiplash
handle(request: http.Request) -> http.Response {
match #(request.method, request.segments()) {
#(http.Get, ["hello", name]) -> http.text(200, "Hello, " + name + "!")
_ -> http.text(404, "Not found")
}
}
main() {
let assert Ok(_) = whiplash.start(whiplash.options(8080), handle)
otp.sleep_forever()
}
module server_test
import main
import pooka/httpc
import pooka/int
import whiplash
test "serves a greeting and returns 404 for an unknown route" {
let assert Ok(server) = whiplash.start(whiplash.options(0), main.handle)
let url = "http://127.0.0.1:" + int.to_string(server.port)
let greeting = httpc.get(url + "/hello/Ada")
let missing = httpc.get(url + "/missing")
whiplash.stop(server)
let assert Ok(greeting) = greeting
let assert Ok(missing) = missing
assert greeting.status == 200
assert greeting.body == <<"Hello, Ada!":utf8>>
assert missing.status == 404
}
Set up the project
pooka new hello_server
cd hello_server
pooka add whiplash
pooka add pooka_http
pooka add pooka_otp
pooka add pooka_httpc --dev
Replace src/main.pooka with the program above and add the test as
test/server.spec.pooka.
Run it
Start the server with pooka run. In another terminal, send two requests:
$ curl -w '\n%{http_code}\n' http://127.0.0.1:8080/hello/Ada
Hello, Ada!
200
$ curl -w '\n%{http_code}\n' http://127.0.0.1:8080/missing
Not found
404
Whiplash binds to the loopback address by default. Press Ctrl-C in the server terminal when you're done.
Test the listener
Run pooka test. The test asks the OS for a free port by passing 0 to
whiplash.options, reads the assigned port from server.port, and sends two
requests through the HTTP client. It stops the listener before checking the
results.
The handler matches the method and path segments together. Only a GET with
exactly two segments, starting with hello, takes the greeting branch. The
fallback covers the other paths and methods.
See the Whiplash guides for TLS, streaming, and WebSockets.