Skip to content

Commit

Permalink
Init code
Browse files Browse the repository at this point in the history
  • Loading branch information
Vennik committed Dec 22, 2016
1 parent 02d62a5 commit d61e6fa
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea/
micro-server.iml
out/
21 changes: 21 additions & 0 deletions src/Main.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import scala.util.matching.Regex

/**
* @author René Vennik
* @version 1.0
* @since 22-12-2016
*/
object Main {

val contact: Regex = """\/contact\/?(.*)?""".r

def main(args: Array[String]): Unit = {
new Server({
case contact(Int(id)) => "Contact int " + id
case contact(String(name)) => "Contact string " + name
case contact(_*) => "Contact nothing"
case "/" => "Home"
}, 80)
}

}
42 changes: 42 additions & 0 deletions src/Server.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import java.net.InetSocketAddress

import com.sun.net.httpserver.{HttpExchange, HttpHandler, HttpServer}

import scala.util.Try

class Server(routes: String => Any, val port: Int = 80) {

val server: HttpServer = HttpServer.create(new InetSocketAddress(port), 0)
val handler = new Handler(routes)
server.createContext("/", handler)
server.setExecutor(null)
server.start()

}

class Handler(val routes: String => Any) extends HttpHandler {

def handle(t: HttpExchange): Unit = {
Try(routes(t.getRequestURI.getPath).toString).toOption match {
case Some(response) => handleResponse(t, 200, response)
case _ => handleResponse(t, 404, "404 - Not Found")
}

}

def handleResponse(t: HttpExchange, rCode: Int, response: String): Unit = {
t.sendResponseHeaders(rCode, response.length())
val os = t.getResponseBody
os.write(response.getBytes)
os.close()
}

}

object Int {
def unapply(i: String): Option[Int] = Try(i.toInt).toOption
}

object String {
def unapply(s: String): Option[String] = Option(s)
}

0 comments on commit d61e6fa

Please sign in to comment.