Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active August 18, 2023 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/ec18d599d20fb560d687b544a6243d2a to your computer and use it in GitHub Desktop.
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/843e8689d72bfecbeaf479c0dd7a2a5262ecd5c5
// 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.3.0"
//> 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