Last active
October 8, 2023 08:15
-
-
Save dacr/d6aa384db87f0937f232c7def099182f to your computer and use it in GitHub Desktop.
ZIO learning - http client using synchronous sttp - shortest usage / published by https://github.com/dacr/code-examples-manager #da8a46e2-cf17-4a81-a072-d3b60b810bf6/333b2be271cf0ac78df691dd124938ec2bff3265
This file contains 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 : ZIO learning - http client using synchronous sttp - shortest usage | |
// keywords : scala, zio, learning, pure-functional, sttp, @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 : da8a46e2-cf17-4a81-a072-d3b60b810bf6 | |
// created-on : 2021-09-26T14:00:32+02:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.3.1" | |
//> using dep "dev.zio::zio:2.0.13" | |
//> using dep "fr.janalyse::zio-worksheet:2.0.13.0" | |
//> using dep "com.softwaremill.sttp.client4::async-http-client-backend-zio:4.0.0-M5" | |
//> using dep "org.slf4j:slf4j-nop:2.0.7" | |
// --------------------- | |
import zio.*, zio.worksheet.* | |
import sttp.client4.* | |
import sttp.client4.asynchttpclient.zio.* | |
object App extends ZIOAppDefault { | |
val logic = for { | |
backend <- ZIO.service[SttpBackend[Task, Any]] | |
result <- backend.send(basicRequest.get(uri"https://mapland.fr/clientInfo")) | |
content <- ZIO.from(result.body) | |
_ <- Console.printLine(content) | |
} yield content | |
// ---------------------------------------------------------------- | |
val wiredLogic = logic.provideLayer(AsyncHttpClientZioBackend.layer()) | |
// ---------------------------------------------------------------- | |
val testingBackend = | |
AsyncHttpClientZioBackend.stub | |
.whenRequestMatches(_.uri.toString() == "https://mapland.fr/clientInfo") | |
.thenRespond("""{"clientIP":"127.0.0.1","userAgent":"curl/42"}""") | |
val stubbedLogic = logic.provide(ZLayer.succeed(testingBackend)) | |
// ---------------------------------------------------------------- | |
override def run = for { | |
_ <- wiredLogic | |
_ <- stubbedLogic | |
} yield () | |
} | |
App.main(Array.empty) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment