Skip to content

Commit 189c367

Browse files
committed
Add server documentation
1 parent 7366281 commit 189c367

File tree

3 files changed

+227
-7
lines changed

3 files changed

+227
-7
lines changed

docs/src/docgen-md.own

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ MODULES = [
3131
"canvas",
3232
"canvasfx",
3333
"forms",
34-
"jdbc"
34+
"jdbc",
35+
"server",
3536

3637
// Android-only
3738
"android",

docs/src/modules/server.yml

Lines changed: 222 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
1+
name: server
2+
since: 2.0.0
3+
scope: desktop
4+
functions:
5+
- name: newServer
6+
args: 'config = {}'
7+
desc: Initializes server using provided config. Returns ServerValue.
8+
desc_ru: Инициализирует сервер, используя заданный конфиг. Возвращает ServerValue.
9+
example: |-
10+
use std, server
11+
12+
newServer()
13+
.get("/", def(ctx) = ctx.json({"message": "Hello, world!"}))
14+
.start(8081)
15+
- name: serve
16+
args: 'port = 8080, dir = "."'
17+
desc: Starts a server on the `port` and hosts the directory `dir`
18+
desc_ru: Запускает сервер на указанном порту и хостит директорию `dir`
19+
example: |-
20+
use server
21+
serve(8083, "./public_html")
22+
types:
23+
- name: ServerValue
24+
functions:
25+
- name: get
26+
args: 'path, handler, roles...'
27+
desc: adds a GET request handler
28+
desc_ru: добавляет обработчик GET запросов
29+
- name: post
30+
args: 'path, handler, roles...'
31+
desc: adds a POST request handler
32+
desc_ru: добавляет обработчик POST запросов
33+
- name: put
34+
args: 'path, handler, roles...'
35+
desc: adds a PUT request handler
36+
desc_ru: добавляет обработчик PUT запросов
37+
- name: patch
38+
args: 'path, handler, roles...'
39+
desc: adds a PATCH request handler
40+
desc_ru: добавляет обработчик PATCH запросов
41+
- name: head
42+
args: 'path, handler, roles...'
43+
desc: adds a HEAD request handler
44+
desc_ru: добавляет обработчик HEAD запросов
45+
- name: delete
46+
args: 'path, handler, roles...'
47+
desc: adds a DELETE request handler
48+
desc_ru: добавляет обработчик DELETE запросов
49+
- name: options
50+
args: 'path, handler, roles...'
51+
desc: adds a OPTIONS request handler
52+
desc_ru: добавляет обработчик OPTIONS запросов
53+
- name: error
54+
args: 'status, handler, contentType = "*"'
55+
desc: adds an error handler
56+
desc_ru: добавляет обработчик ошибок
57+
- name: exception
58+
args: 'className, handler'
59+
desc: adds an exception handler
60+
desc_ru: добавляет обработчик исключений
61+
- name: start
62+
args: 'port = 8080, host = ""'
63+
desc: Starts a server. Use `port` 0 to start a server on a random port.
64+
desc_ru: Запускает сервер. Укажите `port` 0, чтобы запустить сервер на случайном порте
65+
- name: stop
66+
args: ''
67+
desc: Stops a server
68+
desc_ru: Останавливает работу сервера
69+
- name: ContextValue
70+
functions:
71+
- name: attribute
72+
args: 'key, value = ""'
73+
desc: gets or sets an attribute by key
74+
desc_ru: получает или устанавливает аттрибут по ключу `key`
75+
- name: basicAuthCredentials
76+
args: ''
77+
desc: returns a basic authorization credentials, an array with two elements — username and password
78+
desc_ru: возвращает простые данные авторизации, массив с двумя элементами — имя пользователя и пароль
79+
example: |-
80+
extract(username, password) = ctx.basicAuthCredentials()
81+
- name: body
82+
args: ''
83+
desc: returns a response body as a string
84+
desc_ru: возвращает тело ответа в виде строки
85+
- name: bodyAsBytes
86+
args: ''
87+
desc: returns a response body as a byte array
88+
desc_ru: возвращает тело ответа в виде массива байт
89+
- name: characterEncoding
90+
args: ''
91+
desc: returns a character encoding from Content-Type if possible
92+
desc_ru: возвращает кодировку символов из заголовка Content-Type, если возможно
93+
- name: cookie
94+
args: 'name, value = "", maxAge = -1'
95+
desc: gets or sets a cookie
96+
desc_ru: получает или устанавливает значение куки
97+
- name: contentLength
98+
args: ''
99+
desc: returns a content length in bytes
100+
desc_ru: возвращает длину контента в байтах
101+
- name: contentType
102+
args: 'contentType = ""'
103+
desc: gets or sets a Content-Type header
104+
desc_ru: получает или устанавливает заголовок Content-Type
105+
- name: contextPath
106+
args: ''
107+
desc: returns a request context path
108+
desc_ru: возвращает путь контекста запроса
109+
- name: endpointHandlerPath
110+
args: ''
111+
desc: returns a matched endpoint handler path
112+
desc_ru: возвращает путь обработчика совпавшего эндпоинта
113+
- name: formParam
114+
args: 'key'
115+
desc: returns a form parameter
116+
desc_ru: возвращает параметр формы
117+
- name: fullUrl
118+
args: ''
119+
desc: returns a full url
120+
desc_ru: возвращает полный адрес
121+
- name: handlerType
122+
args: ''
123+
desc: returns a current handler type
124+
desc_ru: возвращает тип текущего обработчика
125+
- name: header
126+
args: 'name, value =""'
127+
desc: gets or sets header
128+
desc_ru: получает или устанавливает заголовок по названию `name`
129+
- name: host
130+
args: ''
131+
desc: returns a host
132+
desc_ru: возвращает имя хоста
133+
- name: html
134+
args: 'html'
135+
desc: sets result to the specified html string. Also sets Content-Type header to text/html
136+
desc_ru: устанавливает указанныую html-строку в качестве результата. Также устанавливает заголовок Content-Type в text/html
137+
- name: ip
138+
args: ''
139+
desc: returns an IP address
140+
desc_ru: возвращает IP адрес
141+
- name: json
142+
args: 'obj'
143+
desc: serializes an object to json string and sets it as the result
144+
desc_ru: сериализует объект в json строку и устанавливает в качестве результата
145+
- name: jsonStream
146+
args: 'obj'
147+
desc: serializes an object to json stream and sets it as the result
148+
desc_ru: сериализует объект в json потом и устанавливает в качестве результата
149+
- name: matchedPath
150+
args: ''
151+
desc: returns a matched request path
152+
desc_ru: возвращает совпавший путь запроса
153+
- name: path
154+
args: ''
155+
desc: returns a request path
156+
desc_ru: возвращает путь запроса
157+
- name: port
158+
args: ''
159+
desc: returns a port number
160+
desc_ru: возвращает номер порта
161+
- name: protocol
162+
args: ''
163+
desc: returns a protocol
164+
desc_ru: возвращает протокол
165+
- name: queryString
166+
args: ''
167+
desc: returns a query string
168+
desc_ru: возвращает строку запроса
169+
- name: redirect
170+
args: 'location, statusCode = 302'
171+
desc: redirects to a location with the given status. By default, the status is 302 FOUND
172+
desc_ru: редиректит на указанный путь с указанным статусом. По умолчанию, статус — 302 FOUND
173+
- name: removeCookie
174+
args: 'name, path = "/"'
175+
desc: removes a cookie by name and path
176+
desc_ru: удаляет куки по имени и пути
177+
- name: render
178+
args: 'filePath, data = {}'
179+
desc: renders a file with specified data and sets it as the result
180+
desc_ru: рендерит файл с указанными данными и устанавливает в качестве результата
181+
- name: result
182+
args: 'value = ""'
183+
desc: gets or sets a result. `value` can be a string or a byte array
184+
desc_ru: получает или устанавливает результат. `value` может быть строкой или массивом байт
185+
- name: statusCode
186+
args: ''
187+
desc: returns a response status code
188+
desc_ru: возвращает код статуса ответа
189+
- name: scheme
190+
args: ''
191+
desc: returns a request scheme
192+
desc_ru: возвращает схему запроса
193+
- name: url
194+
args: ''
195+
desc: returns a request url
196+
desc_ru: возвращает адрес запроса
197+
- name: userAgent
198+
args: ''
199+
desc: returns an User-Agent header
200+
desc_ru: возвращает заголовок User-Agent
201+
- name: Config
202+
desc: |-
203+
{
204+
"webjars": true,
205+
"classpathDirs": ["dir1", "dir2"],
206+
"externalDirs": ["dir1", "dir2"],
207+
208+
"asyncTimeout": 6_000,
209+
"defaultContentType": "text/plain",
210+
"etags": true,
211+
"maxRequestSize": 1_000_000,
212+
213+
"caseInsensitiveRoutes": true,
214+
"ignoreTrailingSlashes": true,
215+
"multipleSlashesAsSingle": true,
216+
"contextPath": "/",
217+
218+
"basicAuth": ["user", "password"],
219+
"dev": true,
220+
"showBanner": false,
221+
"sslRedirects": true
222+
}

modules/server/src/main/java/com/annimon/ownlang/modules/server/ServerValue.java

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,14 @@ private void init() {
3333

3434
private Value error(Value[] args) {
3535
Arguments.checkOrOr(2, 3, args.length);
36-
final int handlerIndex;
3736
final String contentType;
3837
if (args.length == 2) {
3938
contentType = "*";
40-
handlerIndex = 1;
4139
} else {
42-
contentType = args[1].asString();
43-
handlerIndex = 2;
40+
contentType = args[2].asString();
4441
}
4542
int status = args[0].asInt();
46-
final Handler handler = toHandler(ValueUtils.consumeFunction(args[handlerIndex], handlerIndex));
43+
final Handler handler = toHandler(ValueUtils.consumeFunction(args[1], 1));
4744
server.error(status, contentType, handler);
4845
return this;
4946
}
@@ -70,7 +67,7 @@ private Value start(Value[] args) {
7067
switch (args.length) {
7168
case 0 -> server.start();
7269
case 1 -> server.start(args[0].asInt());
73-
case 2 -> server.start(args[0].asString(), args[1].asInt());
70+
case 2 -> server.start(args[1].asString(), args[0].asInt());
7471
}
7572
return this;
7673
}

0 commit comments

Comments
 (0)