-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModem.scala
More file actions
58 lines (47 loc) · 1.65 KB
/
Modem.scala
File metadata and controls
58 lines (47 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import scala.io.StdIn.readLine
import scalaz.concurrent.Task
import scalaz.\/-
import scalaz.-\/
import org.http4s._
import org.http4s.dsl._
import org.http4s.server.Server
import org.http4s.server.blaze._
/**
* Immitates a Motorola SURFboard 6141 cable modem by
* serving static files scraped from the real thing.
*
* Could have extended `ServerApp` to reduce the amount
* of code, but making things a bit more explicit for
* discussion purposes.
*/
object Modem {
private val logger = org.log4s.getLogger
private val ConnectorPoolSize = 2 // plenty to imitate a cable modem
private val StaticExtensions = List("htm", "js", "gif")
private val IndexPage = Uri.unsafeFromString("/index.htm")
def main(args: Array[String]) {
val fakeModem = HttpService {
case request @ GET -> Root => TemporaryRedirect(IndexPage)
case request @ GET -> path ~ ext if StaticExtensions.contains(ext) =>
serve(s"$path.$ext", request)
}
val serverTask: Task[Server] = BlazeBuilder.bindHttp(8080, "localhost")
.withConnectorPoolSize(ConnectorPoolSize)
.mountService(fakeModem, "/")
.start
serverTask.unsafePerformSyncAttempt match {
case \/-(server) => awaitShutdown(server)
case -\/(ex) => logger.error(ex)("Failed to start server.")
}
}
def serve(file: String, request: Request): Task[Response] = {
val path = s"/modem/demo$file"
logger.debug(s"Serving $path for request $request")
StaticFile.fromResource(path, Some(request))
.map(Task.now).getOrElse(NotFound())
}
def awaitShutdown(server: Server) = {
readLine("Press enter to stop server.")
server.shutdownNow()
}
}