Skip to content

Instantly share code, notes, and snippets.

@ptitfred ptitfred/Tim.scala
Last active Dec 15, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.