Last active
May 25, 2024 10:19
-
-
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/55bd88c6c4c8903cfea60cb23ae917aa40c1fd14
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 : 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.4.2" | |
//> 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