Pudu programming language
Menu
Package

@chrismichaelps / pudu-lang-httpclient

Named HTTP clients for Pudu: a client factory, delegating handlers, pooled keep-alive connections, handler lifetimes, logging, and resilience

0.1.1Apache-2.01

InstallClose

Endpoints.pudu

Pudu47 lines2.2 KB

GitHub ↗
1/** @Examples.Endpoints.Program — declarative endpoints filled from arguments and read as JSON */2module Endpoints34import Std.Concurrent as Concurrent5import Std.Http as Http6import Std.Http.Server.Reply as Reply7import Std.Http.Server.Route as Route8import Std.Http.Server as Server9import Std.Io as Io10import Std.Json as Json11import Std.Option as Option12import PuduLangHttpClient.Endpoint as Endpoint13import PuduLangHttpClient.Factory.Builder as Builder14import PuduLangHttpClient.Factory as Factory15import PuduLangHttpClient as HttpClient1617/** @Examples.Endpoints.Repository — one repository as the service describes it */18type Repository = { owner: Str, name: Str, stars: Int } derives Json.Encode, Json.Decode1920/// The repository of an owner, by name.21const REPOSITORY: Endpoint.Endpoint = Endpoint.Endpoint{method: Http.Get, template: "repos/:owner/:name"}2223/// Starts a local service of repositories and answers its address.24fn serve() -> (Server.Running, Str) {25  let running = match Server.start("127.0.0.1", 0) {26    case Ok(found) => found27    case Err(problem) => panic(show(problem))28  }29  let server = Server.server(&Route.routing(&[Route.get("/repos/:owner/:name", |request: Route.Request| Reply.json(200, "\{\"owner\":\"" + Option.unwrapOr(Route.param(&request, "owner"), "") + "\",\"name\":\"" + Option.unwrapOr(Route.param(&request, "name"), "") + "\",\"stars\":42\}"))]))30  let _serving = Concurrent.start(fn() -> () { let _ran = Server.run(&server, &running, 0) })31  (running, "http://127.0.0.1:" + show(Server.portOf(&running)) + "/")32}3334/// Calls a declared endpoint and answers 0 when the value read back is the one described.35fn main() -> Int {36  let (running, base) = serve()37  let factory = match Factory.build([Builder.named("code").withBaseAddress(base)]) {38    case Ok(built) => built39    case Err(invalid) => panic(Factory.explain(&invalid))40  }41  let found: HttpClient.Outcome[Repository] = Endpoint.call(&Factory.createClient(&factory, "code"), &REPOSITORY, &[("owner", "chrismichaelps"), ("name", "pudu-lang")])42  let _said = Io.writeLine(show(found))43  Factory.dispose(&factory)44  let _stopped = Server.stop(&running)45  if found == Ok(Repository{owner: "chrismichaelps", name: "pudu-lang", stars: 42}) { 0 } else { 1 }46}47