Browse Source

docs uploaded.

SakiKawasaki 5 years ago
parent
commit
cabd55bf6c

+ 0 - 5
.gitignore

@@ -1,5 +0,0 @@
-nimcache/
-nimblecache/
-htmldocs/
-
-*.exe

+ 0 - 21
LICENSE

@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2020 Ethosa
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.

+ 0 - 48
README.md

@@ -1,48 +0,0 @@
-<h1 align="center">Akane</h1>
-<div align="center">The Nim asynchronous web framework.
-
-[![Open Source Love](https://badges.frapsoft.com/os/v1/open-source.png?v=103)](https://github.com/ellerbrock/open-source-badges/)
-[![Nim language-plastic](https://github.com/Ethosa/yukiko/blob/master/nim-lang.svg)](https://github.com/Ethosa/yukiko/blob/master/nim-lang.svg)
-[![License](https://img.shields.io/github/license/Ethosa/akane)](https://github.com/Ethosa/akane/blob/master/LICENSE)
-
-<h4>Latest version - 0.0.4</h4>
-<h4>Stable version - ?</h4>
-</div>
-
-# Install
--   `git`: `nimble install https://github.com/Ethosa/akane.git`
-
-
-# Features
--   Pages with URL handling methods: `equals`, `startswith`, `endswith`, `regex`,`notfound`.
--   `templates` folder.
--   Only the standard library used.
--   Debug mode.
--   Simple usage
-    ```nim
-    import akane
-
-    proc main =  # for gcsafe
-      var server = newServer(debug=true)  # launch on http://localhost:5000
-
-      server.pages:
-        equals("/"):  # when url is "http://...localhost:5000/"
-          # type of `request` is a Request.
-          await request.answer("Hello, world!")  # utf-8 encoded message.
-
-      server.start()
-    main()
-    ```
-
-
-# FAQ
-*Q*: Where I can learn this?  
-*A*: You can see [wiki page](https://github.com/Ethosa/akane/wiki/Getting-started)
-
-*Q*: How I can help to develop this project?  
-*A*: You can put a :star: :3
-
-
-<div align="center">
-  Copyright 2020 Ethosa
-</div>

+ 0 - 10
akane.nimble

@@ -1,10 +0,0 @@
-[Package]
-name = "akane"
-author = "Ethosa"
-version = "0.0.4"
-description = "The Nim asynchronous web framework."
-license = "MIT"
-srcDir = "akane"
-
-[Deps]
-Requires: "nim >= 1.0.0"

File diff suppressed because it is too large
+ 11 - 0
akane/akane.html


+ 0 - 345
akane/akane.nim

@@ -1,345 +0,0 @@
-# author: Ethosa
-# ----- CORE ----- #
-import asyncdispatch
-import asynchttpserver
-
-# ----- SUPPORT ----- #
-import asyncfile  # loadtemplate
-import strutils  # startsWith, endsWith
-import tables
-import macros
-import times
-import json  # urlParams
-import uri  # decodeUrl
-import os
-import re  # regex
-
-# ----- EXPORT -----
-export asyncdispatch
-export asynchttpserver
-export strutils
-export json
-export uri
-export re
-
-
-type
-  ServerRef* = ref object
-    port*: uint16
-    address*: string
-    server*: AsyncHttpServer
-
-
-var AKANE_DEBUG_MODE*: bool = false  ## change it with `newServer proc<#newServer,string,uint16,bool>`_
-
-
-proc newServer*(address: string = "127.0.0.1",
-                port: uint16 = 5000, debug: bool = false): ServerRef =
-  ## Creates a new ServerRef object.
-  ##
-  ## Arguments:
-  ## -   ``address`` - server address, e.g. "127.0.0.1"
-  ## -   ``port`` - server port, e.g. 5000
-  ## -   ``debug`` - debug mode
-  if not existsDir("templates"):
-    createDir("templates")
-  AKANE_DEBUG_MODE = debug
-  return ServerRef(
-    address: address, port: port,
-    server: newAsyncHttpServer()
-  )
-
-
-proc loadtemplate*(name: string, json: JsonNode = %*{}): Future[string] {.async, inline.} =
-  ## Loads HTML template from `templates` folder.
-  ##
-  ## Arguments:
-  ## -   ``name`` - template's name, e.g. "index", "api", etc.
-  ## -   ``json`` - Json data, which replaces in the template.
-  var
-    file = openAsync(("templates" / name) & ".html")
-    readed = await file.readAll()
-  file.close()
-  for key, value in json.pairs:
-    let
-      # if statment, e.g.: if $(variable) {......}
-      if_stmt = re("if\\s*(\\$\\(" & key & "\\))\\s*\\{\\s*([\\s\\S]+?)\\s*\\}")
-      # variable statment, e.g.: $(variable)
-      variable_stmt = re("(\\$\\s*\\(" & key & "\\))")
-    if readed.contains(if_stmt):
-      var canplace: bool = false
-      case value.kind:
-      of JBool:
-        if value.getBool:
-          canplace = true
-      of JInt:
-        if value.getInt != 0:
-          canplace = true
-      of JFloat:
-        if value.getFloat != 0.0:
-          canplace = true
-      of JString:
-        if value.getStr.len > 0:
-          canplace = true
-      of JArray:
-        if value.len > 0:
-          canplace = true
-      of JObject:
-        if value.getFields.len > 0:
-          canplace = true
-      else: discard
-      if canplace:
-        readed = readed.replacef(if_stmt, "$2")
-      else:
-        readed = readed.replacef(if_stmt, "")
-    readed = readed.replacef(variable_stmt, $value)
-  return readed
-
-
-proc parseQuery*(request: Request): Future[JsonNode] {.async.} =
-  ## Decodes query.
-  ## e.g.:
-  ##   "a=5&b=10" -> {"a": "5", "b": "10"}
-  ##
-  ## This also have debug output, if AKANE_DEBUG_MODE is true.
-  var data = request.url.query.split("&")
-  result = %*{}
-  for i in data:
-    let timed = i.split("=")
-    if timed.len > 1:
-      result[decodeUrl(timed[0])] = %decodeUrl(timed[1])
-  if AKANE_DEBUG_MODE:
-    let
-      now = times.local(times.getTime())
-      timed_month = ord(now.month)
-      month = if timed_month > 9: $timed_month else: "0" & $timed_month
-      day = if now.monthday > 9: $now.monthday else: "0" & $now.monthday
-      hour = if now.hour > 9: $now.hour else: "0" & $now.hour
-      minute = if now.minute > 9: $now.minute else: "0" & $now.minute
-      second = if now.second > 9: $now.second else: "0" & $now.second
-      host =
-        if request.headers.hasKey("host") and request.headers["host"].len > 1:
-          request.headers["host"] & " "
-        else:
-          "new "
-    echo(
-      host, request.reqMethod,
-      " at ", now.year, ".", month, ".", day,
-      " ", hour, ":", minute, ":", second,
-      " Request from ", request.hostname,
-      " to url \"", decodeUrl(request.url.path), "\".")
-
-
-macro pages*(server: ServerRef, body: untyped): untyped =
-  ## This macro provides convenient page adding.
-  ##
-  ## `body` should be StmtList.
-  ## page type can be:
-  ## -   ``equals``
-  ## -   ``startswith``
-  ## -   ``endswith``
-  ## -   ``regex``
-  ## -   ``notfound`` - this page uses without URL argument.
-  ##
-  ## ..code-block::Nim
-  ##  server.pages:
-  ##    equals("/home"):
-  ##      echo url
-  ##      echo urlParams
-  var
-    stmtlist = newStmtList()
-    notfound_declaration = false
-  stmtlist.add(
-    newNimNode(nnkLetSection).add(  # let urlParams: JsonNode = await parseQuery(request)
-      newNimNode(nnkIdentDefs).add(
-        ident("urlParams"),
-        ident("JsonNode"),
-        newCall(
-          "await",
-          newCall(
-            "parseQuery",
-            ident("request")
-          )
-        )
-      )
-    ),
-    newNimNode(nnkLetSection).add(  # let decode_url: string = decodeUrl(request.url.path)
-      newNimNode(nnkIdentDefs).add(
-        ident("decoded_url"),
-        ident("string"),
-        newCall(
-          "decodeUrl",
-          newNimNode(nnkDotExpr).add(
-            newNimNode(nnkDotExpr).add(
-              ident("request"), ident("url")
-            ),
-            ident("path")
-          )
-        )
-      )
-    )
-  )
-  stmtlist.add(newNimNode(nnkIfStmt))
-  var ifstmtlist = stmtlist[2]
-
-  for i in body:  # for each page in statment list.
-    let
-      current = $i[0]
-      path = if i.len == 3: i[1] else: newEmptyNode()
-      slist = if i.len == 3: i[2] else: i[1]
-    if (i.kind == nnkCall and i[0].kind == nnkIdent and
-        (path.kind == nnkStrLit or path.kind == nnkCallStrLit or path.kind == nnkEmpty) and
-        slist.kind == nnkStmtList):
-      if current == "equals":
-        slist.insert(0,  # let url: string = `path`
-            newNimNode(nnkLetSection).add(
-              newNimNode(nnkIdentDefs).add(
-                ident("url"),
-                ident("string"),
-                path
-              )
-            )
-          )
-        ifstmtlist.add(  # request.path.url == i[1]
-          newNimNode(nnkElifBranch).add(
-            newCall("==", path, ident("decoded_url")),
-            slist))
-      elif current == "startswith":
-        slist.insert(0,  # let url = decoded_url[`path`.len..^1]
-          newNimNode(nnkLetSection).add(
-            newNimNode(nnkIdentDefs).add(
-              ident("url"),
-              ident("string"),
-              newCall(
-                "[]",
-                ident("decoded_url"),
-                newCall(
-                  "..^",
-                  newCall("len", path),
-                  newLit(1))
-              )
-            )
-          )
-        )
-        ifstmtlist.add(  # decode_url.startsWith(`path`)
-          newNimNode(nnkElifBranch).add(
-            newCall(
-              "startsWith",
-              ident("decoded_url"),
-              path),
-            slist))
-      elif current == "endswith":
-        slist.insert(0,  # let url: string = decoded_url[0..^`path`.len]
-          newNimNode(nnkLetSection).add(
-            newNimNode(nnkIdentDefs).add(
-              ident("url"),
-              ident("string"),
-              newCall(
-                "[]",
-                ident("decoded_url"),
-                newCall(
-                  "..^",
-                  newLit(0),
-                  newCall("+", newLit(1), newCall("len", path))
-                )
-              )
-            )
-          )
-          )
-        ifstmtlist.add(  # decode_url.endsWith(`path`)
-          newNimNode(nnkElifBranch).add(
-            newCall(
-              "endsWith",
-              ident("decoded_url"),
-              path),
-            slist))
-      elif current == "regex":
-        slist.insert(0,  # discard match(decoded_url, `path`, url)
-            newNimNode(nnkDiscardStmt).add(
-              newCall("match", ident("decoded_url"), path, ident("url"))
-            )
-          )
-        slist.insert(0,  # var url: array[20, string]
-          newNimNode(nnkVarSection).add(
-            newNimNode(nnkIdentDefs).add(
-              ident("url"),
-              newNimNode(nnkBracketExpr).add(
-                ident("array"), newLit(20), ident("string")
-              ),
-              newEmptyNode()
-            )
-          ))
-        ifstmtlist.add(  # decode_url.match(`path`)
-          newNimNode(nnkElifBranch).add(
-            newCall("match", ident("decoded_url"), path),
-            slist))
-      elif current == "notfound":
-        notfound_declaration = true
-        ifstmtlist.add(newNimNode(nnkElse).add(slist))
-
-  if not notfound_declaration:
-    ifstmtlist.add(
-      newNimNode(nnkElse).add(
-        newCall(  # await request.respond(Http404, "Not found")
-          "await",
-          newCall(
-            "respond",
-            ident("request"),
-            ident("Http404"),
-            newLit("Not found"))
-          )
-        )
-      )
-
-  result = newNimNode(nnkProcDef).add(
-    ident("receivepages"),  # procedure name.
-    newEmptyNode(),  # for template and macros
-    newEmptyNode(),  # generics
-    newNimNode(nnkFormalParams).add(  # proc params
-      newEmptyNode(),  # return type
-      newNimNode(nnkIdentDefs).add(  # param
-        ident("request"),  # param name
-        ident("Request"),  # param type
-        newEmptyNode()  # param default value
-      )
-    ),
-    newNimNode(nnkPragma).add(  # pragma declaration
-      ident("async"),
-      ident("gcsafe")
-    ),
-    newEmptyNode(),
-    stmtlist)
-
-
-macro answer*(request, message: untyped, http_code = Http200): untyped =
-  ## Responds from server with utf-8.
-  ##
-  ## Translates to:
-  ##   await request.respond(Http200, "<head><meta charset='utf-8'></head>" & message)
-  result = newCall(
-    "respond",
-    request,
-    http_code,
-    newCall("&", newLit("<head><meta charset='utf-8'></head>"), message)
-  )
-
-
-macro error*(request, message: untyped, http_code = Http404): untyped =
-  ## Responds from server with utf-8.
-  ##
-  ## Translates to:
-  ##   await request.respond(Http404, "<head><meta charset='utf-8'></head>" & message)
-  result = newCall(
-    "respond",
-    request,
-    http_code,
-    newCall("&", newLit("<head><meta charset='utf-8'></head>"), message)
-  )
-
-
-macro start*(server: ServerRef): untyped =
-  ## Starts server.
-  result = quote do:
-    if AKANE_DEBUG_MODE:
-      echo "Server starts on http://", `server`.address, ":", `server`.port
-    waitFor `server`.server.serve(Port(`server`.port), receivepages)

+ 0 - 13
tests/test1/main.nim

@@ -1,13 +0,0 @@
-# author: Ethosa
-# Hello world prorgam.
-import akane
-
-let server = newServer("127.0.0.1", 5000, debug=true)  # default params
-
-
-server.pages:
-  equals("/helloworld"):  # when url is "domain/helloworld"
-    await request.answer "Hello, World!"  # sends utf-8 encoded message.
-
-
-server.start()  # Starts server.

+ 0 - 1
tests/test1/nim.cfg

@@ -1 +0,0 @@
---path:"../../akane"

+ 0 - 14
tests/test2/main.nim

@@ -1,14 +0,0 @@
-# author: Ethosa
-# Templates.
-import akane
-
-var server = newServer()
-
-
-server.pages:
-  equals("/"):  # when url is "domain/"
-    var index = await loadtemplate("index")
-    await request.answer(index)
-
-
-server.start()  # Starts server.

+ 0 - 1
tests/test2/nim.cfg

@@ -1 +0,0 @@
---path:"../../akane"

+ 0 - 12
tests/test2/templates/index.html

@@ -1,12 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-  <title>templates</title>
-  <meta charset="utf-8">
-</head>
-<body>
-  <div align="center">
-    Template test
-  </div>
-</body>
-</html>

+ 0 - 21
tests/test3/main.nim

@@ -1,21 +0,0 @@
-# author: Ethosa
-# equals, startswith, endswith, notfound and regex.
-import akane
-
-var server = newServer(debug=true)
-
-
-server.pages:
-  equals("/helloworld"):  # when url is "domain/helloworld"
-    await request.answer("Hello, World!")
-  startswith("/get"):  # when url is "domain/get...", try "domain/get100000"
-    await request.answer("I see only \"" & url & "\"")  # url var, contains text after "/get".
-  endswith("/info"):  # when url is ".../info", try "domain/user/info"
-    await request.answer("I see only \"" & url & "\"")  # url var, contains text before "/info".
-  regex(re"\A\/id(\d+)\z"):  # when url is re"domain/id\d+", try "domain/id123" and "domain/idNotNumber"
-    await request.answer("Hello, user with ID" & url[0])  # url var contains array[20, string], matched from URL.
-  notfound:  # `notfound` should be at the end of the remaining cases
-    await request.error("<h1 align='center'>Sorry, but page not found :(</h1>")  # `error` sends Http404 code.
-
-
-server.start()  # Starts server.

+ 0 - 1
tests/test3/nim.cfg

@@ -1 +0,0 @@
---path:"../../akane"

+ 0 - 27
tests/test4/main.nim

@@ -1,27 +0,0 @@
-# author: Ethosa
-# Working with templates.
-import akane
-
-
-proc main =  # main proc for gcsafe
-  var
-    server = newServer(debug=true)
-    data: JsonNode = %{
-      "myvariable": %0,
-      "can_place": %false
-    }
-
-  server.pages:
-    equals("/"):  # when url is "domain/"
-      let index = await loadtemplate("index", data)
-      # all "$(myvariable)" in template file replaces at data["myvariable"]
-      data["myvariable"] = %(data["myvariable"].num + 1)
-      if data["myvariable"].num > 3:
-        data["can_place"] = %true
-      await request.answer(index)
-    notfound:
-      await request.error("<h1 align='center'>Sorry, but page not found :(</h1>")
-
-  server.start()  # Starts server.
-
-main()

+ 0 - 1
tests/test4/nim.cfg

@@ -1 +0,0 @@
---path:"../../akane"

+ 0 - 13
tests/test4/templates/index.html

@@ -1,13 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-  <title>Templates Test</title>
-</head>
-<body>
-  <h1 align="center">Now the value is $(myvariable)</h1>
-  if $(can_place)
-  {
-    <h1 align="center">Can place is "true"</h1>
-  }
-</body>
-</html>

Some files were not shown because too many files changed in this diff