|
1 package sqwl.cms |
|
2 |
|
3 import akka.actor.ActorSystem |
|
4 import akka.http.scaladsl.Http |
|
5 import akka.http.scaladsl.model.headers.{ETag, EntityTag} |
|
6 import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpHeader, HttpResponse} |
|
7 import akka.http.scaladsl.server.Directives._ |
|
8 import akka.stream.{ActorMaterializer, Materializer} |
|
9 |
|
10 import scala.collection.immutable |
|
11 import scala.concurrent.ExecutionContextExecutor |
|
12 import scala.io.StdIn |
|
13 |
|
14 trait Server extends App with Service with config with UrlScheme { |
|
15 override implicit val system: ActorSystem = ActorSystem() |
|
16 override implicit val executor: ExecutionContextExecutor = system.dispatcher |
|
17 override implicit val materializer: Materializer = ActorMaterializer() |
|
18 |
|
19 protected def content: iContent |
|
20 |
|
21 val asArticle = Segment.flatMap(content.articleByPath(_)) |
|
22 val asCategory = Segment.flatMap(content.categoryByPath(_)) |
|
23 val asTag = Segment.flatMap(content.tagByPath(_)) |
|
24 |
|
25 private def asHtml(st: ViewState): HttpResponse = { |
|
26 val s = Layout(content, st).render |
|
27 HttpResponse( |
|
28 headers = immutable.Seq[HttpHeader](ETag(MD5(s))), |
|
29 entity = HttpEntity(ContentTypes.`text/html(UTF-8)`, |
|
30 "<!DOCTYPE html>" + s)) |
|
31 } |
|
32 |
|
33 private val routes = get { |
|
34 pathPrefix(http.prefix) { |
|
35 pathEnd { |
|
36 complete(asHtml(Dashboard)) |
|
37 } ~ pathPrefix(asArticle) { article => |
|
38 pathEnd { |
|
39 complete(asHtml(ViewArticle(article))) |
|
40 } ~ getFromDirectory(article.assets.toString) |
|
41 } ~ path(asCategory) { category => |
|
42 complete(asHtml(ViewCategory(category))) |
|
43 } ~ path(TAG / asTag) { tag => |
|
44 complete(asHtml(ViewTag(tag))) |
|
45 } |
|
46 } ~ pathPrefix(http.prefix / ASSETS) { |
|
47 getFromResourceDirectory("META-INF/resources/webjars") |
|
48 } ~ pathPrefix(http.prefix / PUBLIC) { |
|
49 getFromResourceDirectory("public") |
|
50 } |
|
51 } |
|
52 |
|
53 Http().bindAndHandle(routes, http.interface, http.port) |
|
54 system.log.info("Click `Enter` to close application...") |
|
55 StdIn.readLine() |
|
56 system.terminate() |
|
57 |
|
58 } |