NIM의 Sinatra와 같은 웹 프레임 워크. Jester는 NIM에서 웹 애플리케이션을 신속하게 생성하기위한 DSL을 제공합니다.
# example.nim
import htmlgen
import jester
routes:
get " / " :
resp h1 ( " Hello world " )다음과 함께 컴파일하고 실행합니다.
cd tests/example
nim c -r example.nim
보기 : LocalHost : 5000
생산에 배치하기 전에 리버스 프록시 뒤에 응용 프로그램을 실행해야합니다. 이 라이브러리는 아직 HTTP 보안 익스플로잇에 대해 강화되지 않으므로 작성된 응용 프로그램은 공개 인터넷에 노출되어서는 안됩니다.
routes:
get " / " :
# do something here. 모든 경로는 routes 블록 내부에 있어야합니다.
노선은 선언 된 순서대로 실행됩니다. 따라서 멈출 때주의하십시오.
경로 경로에는 특수 패턴 또는 정적 문자열이 포함될 수 있습니다. 특수 패턴은 Sinatra와 거의 동일하며, 유일한 차이점은 다음 대신 @ 를 사용하는 것입니다 :
get " /hello/@name " :
# This matches "/hello/fred" and "/hello/bob".
# In the route ``@"name"`` will be either "fred" or "bob".
# This can of course match any value which does not contain '/'.
resp " Hello " & @ " name "Jester의 패턴은 현재 조금 더 제한되어 있으며 와일드 카드 패턴이 없습니다.
'?'를 사용할 수 있습니다. 선택적 경로 부품을 나타내는 문자.
get " /hello/@name? " :
# This will match what the previous code example matches but will also match
# "/hello/".
if @ " name " == " " :
resp " No name received :( "
else :
resp " Hello " & @ " name "이 경우 선행 '/'선택 사항도 "/hello/?@name?"로 변경하여이를 수행 할 수 있습니다. 주요 '/'가 선택 사항이없는 경우 Jester가 "/hello"와 일치하지 않기 때문에 유용합니다.
REGEX는 또한 경로 패턴으로 사용할 수 있습니다. 하위 패턴 캡처는 request.matches 에 배치됩니다. 경로가 일치하면 일치합니다. 예를 들어:
get re " ^ /([0-9]{2}) .html$ " :
resp request.matches[ 0 ] 이것은 /15.html 양식의 URL과 일치합니다. 이 경우 request.matches[0] 은 15 입니다.
Jester는 조건을 지원하지만 간단한 cond 템플릿으로 제한됩니다.
routes:
get " /@name " :
cond @ " name " == " daniel "
# ``cond`` will pass execution to the next matching route if @"name" is not
# "daniel".
resp " Correct, my name is daniel. "
get " /@name " :
# This will be the next route that is matched.
resp " No, that's not my name. " 경로 기관에는 모두 암시 적 request 객체가 있습니다. 이 개체는 Jester.nim에 문서화되어 있으며 nim doc jester.nim 실행하여 문서를 생성 할 수 있습니다.
경로에서 응답을 반환하는 것은 다음 기능 중 하나를 사용하여 수행해야합니다.
resp 함수 중 하나입니다.body , headers 및/또는 status 설정하고 전화 return 설정함으로써.redirectattachment 기능더있을 수 있습니다. 자세한 내용은 Jester.nim의 문서를 살펴보십시오.
routes 를 사용하지 않고 직접 라우팅을 수행 할 수 있습니다.
자신의 match 절차를 작성하여이를 수행 할 수 있습니다. 이 작업을 수행하는 방법에 대한 예를 보려면 Example2를 살펴보십시오.
기본적으로 Jester는 ./public 의 정적 파일을 찾습니다. setStaticDir 함수를 사용하여 재정의 할 수 있습니다. 파일은 다음과 같이 제공됩니다.
./public/css/style.css- -> http://example.com/css/style.css
참고 : Jester는 others 이 읽을 수있는 파일 만 제공합니다. Unix/Linux에서는 chmod o+r ./public/css/style.css 로이를 확인할 수 있습니다.
setCookie 기능을 사용하여 쿠키를 설정할 수 있습니다.
get " / " :
# Set a cookie "test:value" and make it expire in 5 days.
setCookie ( " test " , @ " value " , daysForward ( 5 )) 그런 다음 Table[string, string] 반환하는 request.cookies 절차를 사용하여 액세스 할 수 있습니다.
요청 객체는 현재 요청에 대한 모든 정보를 보유합니다. request 변수를 사용하여 경로에서 액세스 할 수 있습니다. 그것은 다음과 같이 정의됩니다.
Request * = ref object
params * : StringTableRef # # Parameters from the pattern, but also the
# # query string.
matches * : array [ MaxSubpatterns , string ] # # Matches if this is a regex
# # pattern.
body * : string # # Body of the request, only for POST.
# # You're probably looking for ``formData``
# # instead.
headers * : StringTableRef # # Headers received with the request.
# # Retrieving these is case insensitive.
formData * : MultiData # # Form data; only present for
# # multipart/form-data
port * : int
host * : string
appName * : string # # This is set by the user in ``run``, it is
# # overriden by the "SCRIPT_NAME" scgi
# # parameter.
pathInfo * : string # # This is ``.path`` without ``.appName``.
secure * : bool
path * : string # # Path of request.
query * : string # # Query string of request.
cookies * : StringTableRef # # Cookies from the browser.
ip * : string # # IP address of the requesting client.
reqMeth * : HttpMethod # # Request method, eg. HttpGet, HttpPost
settings * : Settings 사용자 정의 라우터를 사용하면 비동기 루프를 시작하기 전에 고유 한 초기화 코드를 실행하고 동적 설정을 제스터로 전달할 수 있습니다.
import asyncdispatch, jester, os, strutils
router myrouter:
get " / " :
resp " It's alive! "
proc main () =
let port = paramStr ( 1 ). parseInt (). Port
let settings = newSettings (port = port)
var jester = initJester (myrouter, settings = settings)
jester. serve ()
when isMainModule :
main ()이 코드는 여기에 제공된 Sinatra의 코드와 매우 유사합니다. http://help.github.com/post-receive-hooks/
import jester, json
routes:
post " / " :
var push = parseJson ( @ " payload " )
resp " I got some JSON: " & $ push