Skip to content

Instantly share code, notes, and snippets.

@ptitfred
Last active December 15, 2015 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptitfred/5250131 to your computer and use it in GitHub Desktop.
Save ptitfred/5250131 to your computer and use it in GitHub Desktop.
Some HTTP server in Scala
package web
import com.sun.net.httpserver._
import java.net.InetSocketAddress
import java.net.Inet4Address
case class Answer(code: Int, body: String)
class MyServer(port: Int) {
type Handler = String => Answer
var httpServer = HttpServer.create(new InetSocketAddress(port), 0)
def map(root: String)(handler: Handler): MyServer = {
httpServer.createContext(root, new HttpHandler {
def handle(httpExchange: HttpExchange) {
println(httpExchange.getRequestURI.getPath)
val response = handler(httpExchange.getRequestURI.getPath)
val bytes = response.body.getBytes
httpExchange.sendResponseHeaders(response.code, bytes.size)
httpExchange.getResponseBody.write(bytes)
}
})
this
}
def start {
println(s"Starting on $port")
httpServer.start
}
}
object MyServer {
def apply(port: Int) = new MyServer(port)
}
object Tim extends App {
MyServer(8080).map("/") {
case "/hello" => Answer(200, "hello")
case path => Answer(404, s"$path Not found")
} start
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment