
Endpoints.pudu
Pudu47 lines2.2 KB
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.Decode192021const REPOSITORY: Endpoint.Endpoint = Endpoint.Endpoint{method: Http.Get, template: "repos/:owner/:name"}222324fn 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}333435fn 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