Created
July 2, 2018 02:54
-
-
Save ryan-williams/baadd42c59f4d0dd1cb9c9732831f4ef to your computer and use it in GitHub Desktop.
Minimal web servers in scala, supporting a simple GET / HEAD endpoint
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
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() |
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
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