base/src/sqwl/cms/Server.scala
changeset 4 1a1347e8c5be
parent 3 48479e4b89d4
child 7 50a354e5bda4
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/base/src/sqwl/cms/Server.scala	Thu Nov 29 12:20:20 2018 +0100
@@ -0,0 +1,58 @@
+package sqwl.cms
+
+import akka.actor.ActorSystem
+import akka.http.scaladsl.Http
+import akka.http.scaladsl.model.headers.{ETag, EntityTag}
+import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpHeader, HttpResponse}
+import akka.http.scaladsl.server.Directives._
+import akka.stream.{ActorMaterializer, Materializer}
+
+import scala.collection.immutable
+import scala.concurrent.ExecutionContextExecutor
+import scala.io.StdIn
+
+trait Server extends App with Service with config with UrlScheme {
+  override implicit val system: ActorSystem = ActorSystem()
+  override implicit val executor: ExecutionContextExecutor = system.dispatcher
+  override implicit val materializer: Materializer = ActorMaterializer()
+
+  protected def content: iContent
+
+  val asArticle = Segment.flatMap(content.articleByPath(_))
+  val asCategory = Segment.flatMap(content.categoryByPath(_))
+  val asTag = Segment.flatMap(content.tagByPath(_))
+
+  private def asHtml(st: ViewState): HttpResponse = {
+    val s = Layout(content, st).render
+    HttpResponse(
+      headers = immutable.Seq[HttpHeader](ETag(MD5(s))),
+      entity = HttpEntity(ContentTypes.`text/html(UTF-8)`,
+      "<!DOCTYPE html>" + s))
+  }
+
+  private val routes = get {
+    pathPrefix(http.prefix) {
+      pathEnd {
+        complete(asHtml(Dashboard))
+      } ~ pathPrefix(asArticle) { article =>
+        pathEnd {
+          complete(asHtml(ViewArticle(article)))
+        } ~ getFromDirectory(article.assets.toString)
+      } ~ path(asCategory) { category =>
+        complete(asHtml(ViewCategory(category)))
+      } ~ path(TAG / asTag) { tag =>
+        complete(asHtml(ViewTag(tag)))
+      }
+    } ~ pathPrefix(http.prefix / ASSETS) {
+      getFromResourceDirectory("META-INF/resources/webjars")
+    } ~ pathPrefix(http.prefix / PUBLIC) {
+      getFromResourceDirectory("public")
+    }
+  }
+
+  Http().bindAndHandle(routes, http.interface, http.port)
+  system.log.info("Click `Enter` to close application...")
+  StdIn.readLine()
+  system.terminate()
+
+}