Last active
May 25, 2024 08:39
-
-
Save dacr/ec18d599d20fb560d687b544a6243d2a to your computer and use it in GitHub Desktop.
parameterized hello world http server (zhttp zio based) using tapir / published by https://github.com/dacr/code-examples-manager #c833c2a8-4fa9-4204-8b4d-c1233b608434/1ece2a1f8f17ff5f2a5fd4c065a5faeb2cd5d27d
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summary : parameterized hello world http server (zhttp zio based) using tapir | |
// keywords : scala, zio, tapir, http, zhttp, endpoints, @testable, @exclusive | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : c833c2a8-4fa9-4204-8b4d-c1233b608434 | |
// created-on : 2021-11-20T15:01:58+01:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// test-with : curl http://127.0.0.1:8080/hello | |
// --------------------- | |
//> using scala "3.4.2" | |
//> using dep "com.softwaremill.sttp.tapir::tapir-core:1.6.0" | |
//> using dep "com.softwaremill.sttp.tapir::tapir-zio-http-server:1.6.0" | |
//> using dep "fr.janalyse::zio-worksheet:2.0.15.0" | |
// --------------------- | |
import sttp.tapir.ztapir.* | |
import sttp.tapir.server.ziohttp.ZioHttpInterpreter | |
import sttp.tapir.Endpoint | |
import zio.http.Server | |
import zio.*, zio.worksheet.* | |
/* | |
curl http://127.0.0.1:8080/hello | |
curl http://127.0.0.1:8080/hi?name=david | |
*/ | |
// -------------------------------------------------- | |
def helloLogic = ZIO.succeed("Hello world") | |
val helloEndPoint = | |
endpoint | |
.in("hello") | |
.out(stringBody) | |
val helloRoute = helloEndPoint.zServerLogic[Any]( _ => helloLogic) | |
// -------------------------------------------------- | |
def hiLogic(name: String) = ZIO.succeed(s"Hi $name") | |
val hiEndPoint = | |
endpoint | |
.in("hi") | |
.in(query[String]("name")) | |
.out(stringBody) | |
val hiRoute = hiEndPoint.zServerLogic[Any](hiLogic) | |
// -------------------------------------------------- | |
val routes = | |
ZioHttpInterpreter() | |
.toHttp(List(helloRoute, hiRoute)) | |
// -------------------------------------------------- | |
Server.serve(routes.withDefaultErrorResponse).provide(Server.default).unsafeRun | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment