Last active
February 3, 2026 20:19
-
-
Save dacr/5149a16dedf6d235c47cd03485c5b75b to your computer and use it in GitHub Desktop.
Testing if a remote http server is reachable. / published by https://github.com/dacr/code-examples-manager #38906815-7ba7-43be-9c46-bded28296193/f84ac8bd160c75aab41b167bbd8068165cbd3efa
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 : Testing if a remote http server is reachable. | |
| // keywords : scala, scalatest, netio, async | |
| // publish : gist | |
| // authors : David Crosson | |
| // license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // id : 38906815-7ba7-43be-9c46-bded28296193 | |
| // created-on : 2019-06-05T20:46:10Z | |
| // managed-by : https://github.com/dacr/code-examples-manager | |
| // run-with : scala-cli $file | |
| // --------------------- | |
| //> using scala "3.4.2" | |
| //> using dep "org.scalatest::scalatest:3.2.16" | |
| //> using objectWrapper | |
| // --------------------- | |
| import org.scalatest.*, matchers.* | |
| import scala.concurrent.* | |
| // TODO requires more tests | |
| // TODO refactor to async approach | |
| def checkRemoteURL(url:String):Future[Boolean] = { | |
| import ExecutionContext.Implicits.global | |
| Future { new java.net.URL(url).openConnection() } | |
| .map { cnx => | |
| cnx.setConnectTimeout(5000) | |
| cnx.setReadTimeout(5000) | |
| cnx.setUseCaches(false) | |
| cnx.setAllowUserInteraction(false) | |
| cnx.connect() | |
| cnx } | |
| .map { _.getInputStream } | |
| .map { scala.io.Source.fromInputStream(_) } | |
| .map { in => in.close()} | |
| .collect { case x => true } | |
| .recover { case _ => false } | |
| } | |
| class RemoteURLTest extends flatspec.AsyncFlatSpec with should.Matchers { | |
| override def suiteName: String = "RemoteURLTest" | |
| "checkRemoteURL" should "return true with valid URL" ignore { | |
| checkRemoteURL("http://httpbin.org").map { result => | |
| result shouldBe true | |
| } | |
| } | |
| it should "return false with invalid URL" ignore { | |
| checkRemoteURL("http://httpbinxx.orgzz").map {result => | |
| result shouldBe false | |
| } | |
| } | |
| } | |
| org.scalatest.tools.Runner.main(Array("-oDF", "-s", classOf[RemoteURLTest].getName)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment