Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 6, 2023 15:39
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/dbfc8d455da5b33b0cb33c5ac981de0d to your computer and use it in GitHub Desktop.
Save dacr/dbfc8d455da5b33b0cb33c5ac981de0d to your computer and use it in GitHub Desktop.
ZIO live session - Writing a more complex application / published by https://github.com/dacr/code-examples-manager #fb874ad4-4adc-489a-95ba-5c16198a8782/90eea93cf029582c5e630ba97c109d722c0e84ca
// summary : ZIO live session - Writing a more complex application
// keywords : scala, zio, live, demo, pure-functional, @testable
// 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 : fb874ad4-4adc-489a-95ba-5c16198a8782
// created-on : 2021-09-26T16:27:18+02:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.2.2"
//> using dep "dev.zio::zio:2.0.13"
//> using dep "com.softwaremill.sttp.client3::async-http-client-backend-zio:3.8.15"
//> using dep "com.softwaremill.sttp.client3::zio-json:3.8.15"
//> using dep "fr.janalyse::zio-worksheet:2.0.13.0"
//> using dep "org.slf4j:slf4j-simple:2.0.7"
// ---------------------
import zio.*
import zio.json.*
import zio.worksheet.*
import sttp.client3.ziojson.*
import sttp.client3.*
import sttp.client3.asynchttpclient.zio.*
case class ClientInfo(clientIP: String, userAgent: String)
object ClientInfo:
implicit val codec: JsonCodec[ClientInfo] = DeriveJsonCodec.gen
// -----------------------------------------------------------------------------------------
val app =
for
_ <- ZIO.log("Application starts")
backend <- ZIO.service[SttpBackend[Task, Any]]
response <- backend.send(basicRequest.get(uri"https://mapland.fr/clientInfo").response(asJson[ClientInfo]))
clientInfo <- ZIO.from(response.body)
_ <- ZIO.log(s"my ip is ${clientInfo.clientIP}")
_ <- ZIO.log("Application ends")
yield clientInfo
app.provideLayer(AsyncHttpClientZioBackend.layer()).unsafeRun
// -----------------------------------------------------------------------------------------
val stub =
AsyncHttpClientZioBackend.stub
.whenRequestMatches(_.uri.toString() == "https://mapland.fr/clientInfo")
.thenRespond("""{"clientIP":"127.0.0.1","userAgent":"curl/42"}""")
app.provideLayer(ZLayer.succeed(stub)).unsafeRun
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment