Skip to content

Instantly share code, notes, and snippets.

@ryan-williams
Created July 2, 2018 02:54
Show Gist options
  • Save ryan-williams/baadd42c59f4d0dd1cb9c9732831f4ef to your computer and use it in GitHub Desktop.
Save ryan-williams/baadd42c59f4d0dd1cb9c9732831f4ef to your computer and use it in GitHub Desktop.
Minimal web servers in scala, supporting a simple GET / HEAD endpoint
import $ivy.`org.http4s::http4s-dsl:0.18.13`
import $ivy.`org.http4s::http4s-blaze-server:0.18.13`
import cats.effect._
import org.http4s._
import org.http4s.dsl.io._
import org.http4s.server.blaze._
val response = "This is the response"
val port = 8000
val service = HttpService[IO] {
case GET -> Root / "test" ⇒ Ok(response)
case HEAD -> Root / "test" ⇒ Ok(response)
}
val builder =
BlazeBuilder[IO]
.bindHttp(port, "localhost")
.mountService(service, "/")
.start
val server = builder.unsafeRunSync()
server.shutdown.unsafeRunSync()
import java.net.InetSocketAddress
import com.sun.net.httpserver.{ HttpExchange, HttpHandler, HttpServer }
val response = "This is the response"
class MyHandler
extends HttpHandler {
def handle(t: HttpExchange): Unit = {
if (t.getRequestMethod == "GET") {
t.sendResponseHeaders(200, response.length)
val os = t.getResponseBody
os.write(response.getBytes)
os.close()
} else if (t.getRequestMethod == "HEAD") {
t.getResponseHeaders.add("Content-Length", response.length.toString)
t.sendResponseHeaders(200, -1)
}
}
}
val port = 8000
val server: HttpServer = HttpServer.create(new InetSocketAddress(port), 0)
server.createContext("/test", new MyHandler)
server.setExecutor(null)
server.start()
server.stop(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment