Last active
December 15, 2015 10:59
-
-
Save ptitfred/5250131 to your computer and use it in GitHub Desktop.
Some HTTP server in Scala
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
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