-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwebb.lua
1605 lines (1360 loc) · 39.3 KB
/
webb.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[==[
webb | main module
Written by Cosmin Apreutesei. Public Domain.
Exports
glue
pp
CONFIG
config'base_url' optional, for absurl()
CONFIG API
config(name[, default_val]) -> val get/set config value
config{name->val} set multiple config values
S_texts(lang, ext) -> s get internationalized strings
update_S_texts(lang, ext, t) update internationalized strings
S(id, en_s, ...) -> s get internationalized string (stub)
REQUEST CONTEXT
once(f, ...) memoize for current request
cx() -> t get per-request shared context
cx().fake -> t|f context is fake (we're on cmdline)
webb.setcx(thread, t) set per-request shared context
webb.env([t]) -> t per-request shared environment
THREADING
newthread(f) -> thread create thread
thread(f, ...) -> thread create and resume thread
resume(thread, ...) -> ... resume thread
suspend() -> ... suspend thread
transfer(thread, ...) -> ... transfer to thread
onthreadfinish(thread, f) add a thread finalizer
ITERATORS
cowrap(f, ...) -> f create iterator
yield(...) -> ... yield from iterator
TIMERS
sleep(n) sleep n seconds
sleep_until(t) sleep until time
sleep_job() -> sj make a sleep job
runat(ts, f) run f at time
runafter(s, f) run f after s seconds
runevery(s, f) run f every s seconds
LOGGING
webb.dbg (module, event, fmt, ...)
webb.note (module, event, fmt, ...)
webb.warnif (module, event, fmt, ...)
webb.logerror (module, event, fmt, ...)
REQUEST
headers([name]) -> s|t get header or all
cookie(name) -> s | nil get cookie value
method([method]) -> s|b get/check http method
post([name]) -> s | t | nil get POST arg or all
upload(file) -> true | nil upload POST data to a file
args([n|name]) -> s | t | nil get path element or GET arg or all
scheme([s]) -> s | t|f get/check request scheme
host([s]) -> s | t|f get/check request host
port([p]) -> p | t|f get/check server port
email(user) -> s get email address of user
client_ip() -> s get client's ip address
googlebot() -> t|f check if UA is the google bot
mobile() -> t|F check if UA is a mobile browser
ARG PARSING
id_arg(s) -> n | nil validate int arg with slug
str_arg(s) -> s | nil validate/trim non-empty string arg
enum_arg(s, values...) -> s | nil validate enum arg
list_arg(s[, arg_f]) -> t validate comma-separated list arg
checkbox_arg(s) -> 'checked' | nil validate checkbox value from html form
url_arg(s) -> t decode url
OUTPUT
outall(s) output a single value
out(s) output one more non-nil value
push_out([f]) push output function or buffer
pop_out() -> s pop output function and flush it
stringbuffer([t]) -> f(s1,...)/f()->s create a string buffer
record(f) -> s run f and collect out() calls
out_buffering() -> t | f check if we're buffering output
setheader(name, val) set a header (unless we're buffering)
setmime(ext) set content-type based on file extension
setcompress(on) enable or disable compression
outprint(...) like Lua's print but uses out()
HTML ENCODING
html(s) -> s escape html
URL ENCODING
url{...} -> t | s encode url
absurl([path]) -> s get the absolute url for a local url
slug(id, s) -> s encode id and s to `s-id`
RESPONSE
http_error(res) raise a http error
redirect(url[, status]) exit with "302 moved temporarily"
checkfound(ret, err) -> ret exit with "404 not found"
checkarg(ret, err) -> ret exit with "400 bad request"
allow(ret, err) -> ret exit with "403 forbidden"
check_etag(s) exit with "304 not modified"
onrequestfinish(f) add a request finalizer
setconnectionclose() close the connection after this request.
SOCKETS
connect(ip, port) -> sock connect to a server
resolve(host) -> ip4 resolve a hostname
HTTP REQUESTS
getpage(url,post_data | opt) -> req make a HTTP request
JSON ENCODING/DECODING
json_arg(s) -> t decode JSON
json(t) -> s encode JSON
null value to encode json `null`
FILESYSTEM
wwwpath(file, [type]) -> path get www subpath (and check if exists)
wwwfile[_cached](file[,parse]) -> s get www file contents
wwwfile.filename <- s|f(filename) set virtual www file contents
wwwfiles([filter]) -> {name->true} list www files
out[www]file[_cached](file[,parse]) buffered output of www file
varpath(file) -> path get var subpath (no check that it exists)
tmppath(file) -> path get tmp subpath (no check that it exists)
varfile.filename <- s|f(filename) set virtual file contents
varfile[_cached](file[,parse]) -> s get var file contents
readfile[_cached](file[,parse]) -> s (cached) readfile for small static files
fileext(s) -> s get file extension (in lowercase)
mkdirs(file) -> file | nil make dirs for file path
fileexists(file, [type]) -> file | nil check if file exists
filemtime(file, [type]) -> mtime get file mtime
filename(filepath) -> file get file name from full path
filedir(filepath) -> dir get dir name from full path
MUSTACHE TEMPLATES
render_string(s, [env], [part]) -> s render a template from a string
render_file(file, [env], [part]) -> s render a template from a file
mustache_wrap(s, name) -> s wrap a template in <script> tag
template(name) -> s get template contents
template.name <- s|f(name) set template contents or handler
render(name[, env]) -> s render template
LUAPAGES TEMPLATES
include_string(s, [env], [name], ...) run LuaPages script
include(file, [env], ...) run LuaPages script
LUA SCRIPTS
run_string(s, [env], args...) -> ret run Lua script
run(file, [env], args...) -> ret run Lua script
HTML FILTERS
filter_lang(s, lang) -> s filter <t> tags and :lang attrs
filter_comments(s) -> s filter <!-- --> comments
FILE CONCATENATION LISTS
catlist_files(s) -> {file1,...} parse a .cat file
outcatlist(file, args...) output a .cat file
MAIL SENDING
sendmail(from, rcpt, subj, msg, html) send email
IMAGE PROCESSING
resize_image(src_path, dst_path, max_w, max_h)
base64_image_src(s)
HTTP SERVER INTEGRATION
webb.respond(req) webb.server response handler
webb.request_finish()
webb.server([opt]) -> server
STANDALONE OPERATION
webb.run(f, ...) run a function in a webb context.
webb.request(req | arg1,...) make a request without a http server.
API DOCS ---------------------------------------------------------------------
once(f)
Memoize function for current request.
webb.env([t]) -> t
Per-request shared environment. Inherits _G. Scripts run with `include()`
and `run()` run in this environment by default. If the `t` argument is given,
an inherited environment is created.
]==]
local ffi = require'ffi'
local glue = require'glue'
local pp = require'pp'
local uri = require'uri'
local errors = require'errors'
local sock = require'sock'
local cjson = require'cjson'
local b64 = require'base64'.encode
local fs = require'fs'
local path = require'path'
local mustache = require'mustache'
local xxhash = require'xxhash'
local prettycjson = require'prettycjson'
local concat = table.concat
local remove = table.remove
local add = table.insert
local update = glue.update
local assertf = glue.assert
local memoize = glue.memoize
local _ = string.format
local format = string.format
_G.glue = glue
_G.pp = pp
webb = {}
errors.errortype'http_response'.__tostring = function(self)
local s = self.traceback or self.message or ''
if self.status then
s = self.status .. ' ' .. s
end
return s
end
function readfile(file, parse)
parse = parse or glue.pass
local s, err = glue.readfile(file)
if not s then return nil, err end
return parse(s)
end
function writefile(file, s, mode)
webb.note('fs', 'writefile', '%s (%s %s)', file,
mode or 'w', type(s) == 'string' and #s..' bytes' or type(s))
local ok, err = glue.writefile(file, s, mode)
if ok then return ok end
webb.logerror('fs', 'writefile', 'failed writing file %s: %s', file, err)
end
--threads and webb context switching -----------------------------------------
--request context for current thread.
local cx do
local thread_cx = setmetatable({}, {__mode = 'k'})
function sock.save_thread_context(thread)
thread_cx[thread] = cx
end
function sock.restore_thread_context(thread)
cx = thread_cx[thread]
end
function _G.cx() return cx end
function webb.setcx(thread, cx1)
thread_cx[thread] = cx1
cx = cx1
end
end
threadenv = sock.threadenv
--from $sock.lua
newthread = sock.newthread
thread = sock.thread
resume = sock.resume
suspend = sock.suspend
transfer = sock.transfer
cowrap = sock.cowrap
yield = sock.yield
currentthread = sock.currentthread
onthreadfinish = sock.onthreadfinish
sleep_until = sock.sleep_until
sleep = sock.sleep
sleep_job = sock.sleep_job
runat = sock.runat
runafter = sock.runafter
runevery = sock.runevery
--config function ------------------------------------------------------------
do
local conf = {}
function config(var, default)
if type(var) == 'table' then
for var, val in pairs(var) do
config(var, val)
end
else
local val = conf[var]
if val == nil then
val = default
conf[var] = val
end
return val
end
end
function with_config(t, f, ...)
local old_conf = conf
local function pass(...)
conf = old_conf
return ...
end
conf = setmetatable(t, {__index = old_conf})
return pass(f(...))
end
end
--multi-language strings -----------------------------------------------------
do
local function s_file(lang, ext)
return varpath(format('%s-s-%s%s.lua', config'app_name', lang,
ext == 'lua' and '' or '-'..ext))
end
local function load_s_file(file)
local f = loadfile(file)
return f and f()
end
local function save_s_file(file, t)
writefile(file, 'return '..pp.format(t, '\t'))
end
local lua_texts = {} --{lang->{id->text}}
local js_texts = {} --{lang->{id->text}}
function S_texts(lang, ext)
local texts = ext == 'lua' and lua_texts or js_texts
local t = texts[lang]
if not t then
local file = s_file(lang, ext)
t = load_s_file(file) or {}
texts[lang] = t
end
return t
end
function update_S_texts(lang, ext, t)
local texts = S_texts(lang, ext)
for k,v in pairs(t) do
texts[k] = v or nil
end
local file = s_file(lang, ext)
save_s_file(file, texts)
end
function S(_, s, ...) --stub, reimplemented in `webb_action`
if select('#', ...) > 0 then
return glue.subst(s, ...)
else
return s
end
end
end
--per-request environment ----------------------------------------------------
--per-request memoization.
function once(f)
return function(...)
local ret = cx[f]
if not ret then
ret = f(...)
cx[f] = ret
end
return ret
end
end
--per-request shared environment to use in all app code.
function webb.env(t)
local env = cx.env
if not env then
env = {__index = _G}
setmetatable(env, env)
cx.env = env
end
if t then
t.__index = env
return setmetatable(t, t)
else
return env
end
end
--logging --------------------------------------------------------------------
function webb.log (...) cx.req.http:log(...) end
function webb.dbg (...) webb.log('' , ...) end
function webb.note (...) webb.log('note' , ...) end
function webb.logerror (...) webb.log('ERROR', ...) end
function webb.warnif (module, event, cond, ...)
if not cond then return end
webb.log('WARN', module, event, ...)
end
function trace(event, s, ...)
if not event then
print(debug.traceback())
return
end
dbg(event, '%4.2f '..s, 0, ...)
local t0 = time()
return function(event, s, ...)
local dt = time() - t0
dbg(event, '%4.2f '..s, dt, ...)
end
end
--request API ----------------------------------------------------------------
function method(which)
if which then
return cx.req.method:lower() == which:lower()
else
return cx.req.method:lower()
end
end
function headers(h)
if h then
return cx.req.headers[h]
else
return cx.req.headers
end
end
function cookie(name)
local t = cx.req.headers.cookie
return t and t[name]
end
function args(v)
local args = cx.args
if not args then
local u = uri.parse(cx.req.uri)
args = u.segments
remove(args, 1)
if u.args then
for i = 1, #u.args, 2 do
local k,v = u.args[i], u.args[i+1]
args[k] = v
end
end
cx.args = args
end
if v then
return args[v]
else
return args
end
end
function post(v)
if not method'post' then
return
end
local post = cx.post
if not post then
local s = cx.req:read_body'string'
local ct = headers'content-type'
if ct then
if ct.media_type == 'application/x-www-form-urlencoded' then
post = uri.parse_args(s)
elseif ct.media_type == 'application/json' then --prevent ENCTYPE CORS
post = json_arg(s)
end
else
post = s
end
cx.post = post
end
if v then
return post[v]
else
return post
end
end
function upload(file)
return glue.fcall(function(finally)
webb.note('webb', 'upload', '%s', file)
local f = assert(fs.open(file..'.tmp', 'w'))
finally(function() f:close() end)
local function write(buf, sz)
assert(f:write(buf, sz))
end
cx.req:read_body(write)
assert(f:close())
assert(fs.move(file..'.tmp', file))
return file
end)
end
function scheme(s)
if s then
return scheme() == s
end
return headers'x-forwarded-proto'
or (cx.req.http.tcp.istlssocket and 'https' or 'http')
end
function host(s)
if s then
return host() == s
end
return headers'x-forwarded-host'
or (headers'host' and headers'host'.host)
or config'host'
or cx.req.http.tcp.local_addr
end
function port(p)
if p then
return port() == tonumber(p)
end
return headers'x-forwarded-port'
or cx.req.http.tcp.local_port
end
function email(user)
return _('%s@%s', assert(user), host())
end
function client_ip()
return headers'x-forwarded-for'
or cx.req.http.tcp.remote_addr
end
function googlebot()
return headers'user-agent':find'googlebot' and true or false
end
function mobile()
return headers'user-agent':find'mobi' and true or false
end
--arg validation & decoding --------------------------------------------------
function id_arg(s)
if not s or type(s) == 'number' then return s end
local n = tonumber(s:match'(%d+)$') --strip any slug
return n and n >= 0 and n or nil
end
function str_arg(s)
s = glue.trim(s or '')
return s ~= '' and s or nil
end
function json_str_arg(s)
return type(s) == 'string' and s or nil
end
function enum_arg(s, ...)
for i=1,select('#',...) do
if s == select(i,...) then
return s
end
end
return nil
end
function list_arg(s, arg_f)
local s = str_arg(s)
if not s then return nil end
arg_f = arg_f or str_arg
local t = {}
for s in glue.gsplit(s, ',', 1, true) do
add(t, arg_f(s))
end
return t
end
function checkbox_arg(s)
return s == 'on' and 'checked' or nil
end
function url_arg(s)
return type(s) == 'string' and uri.parse(s) or s
end
--output API -----------------------------------------------------------------
function outall(s)
if cx.http_out or out_buffering() then
out(s)
else
cx.res.content = s ~= nil and tostring(s) or ''
cx.req:respond(cx.res)
end
end
function out_buffering()
return cx.outfunc ~= nil
end
local function default_outfunc(s, len)
if s == nil or s == '' or len == 0 then
return
end
if not cx.http_out then
cx.res.want_out_function = true
cx.http_out = cx.req:respond(cx.res)
end
s = type(s) ~= 'cdata' and tostring(s) or s
cx.http_out(s, len)
end
function stringbuffer(t)
t = t or {}
return function(...)
local n = select('#',...)
if n == 0 then --flush it
return concat(t)
else
local s, len = ...
if s == nil or s == '' or len == 0 then
return
end
if type(s) == 'cdata' then
assert(len)
s = ffi.string(s, len)
else
assert(not len)
s = tostring(s)
end
t[#t+1] = s
end
end
end
function push_out(f)
cx.outfunc = f or stringbuffer()
if not cx.outfuncs then
cx.outfuncs = {}
end
add(cx.outfuncs, cx.outfunc)
end
function pop_out()
if not cx.outfunc then return end
local s = cx.outfunc()
local outfuncs = cx.outfuncs
remove(outfuncs)
cx.outfunc = outfuncs[#outfuncs]
return s
end
function out(s, len)
local outfunc = cx.outfunc or default_outfunc
outfunc(s, len)
end
local function pass_record(...)
return pop_out(), ...
end
function record(f, ...)
push_out()
return pass_record(f(...))
end
local function _outfile(readfile, path, parse)
out(readfile(path, parse)) --TODO: make it buffered
end
function outfile(path, parse) return _outfile(readfile, path, parse) end
function outfile_cached(path, parse) return _outfile(readfile_cached, path, parse) end
function setheader(name, val)
cx.res.headers[name] = val
end
mime_types = {
html = 'text/html',
txt = 'text/plain',
sh = 'text/plain',
css = 'text/css',
json = 'application/json',
js = 'application/javascript',
jpg = 'image/jpeg',
jpeg = 'image/jpeg',
png = 'image/png',
gif = 'image/gif',
ico = 'image/x-icon',
svg = 'image/svg+xml',
ttf = 'font/ttf',
woff = 'font/woff',
woff2= 'font/woff2',
pdf = 'application/pdf',
zip = 'application/zip',
gz = 'application/x-gzip',
tgz = 'application/x-gzip',
xz = 'application/x-xz',
bz2 = 'application/x-bz2',
tar = 'application/x-tar',
mp3 = 'audio/mpeg',
events = 'text/event-stream',
}
function setmime(ext)
cx.res.content_type = checkfound(mime_types[ext])
end
function setcompress(on)
cx.res.compress = on
end
do
local function print_wrapper(print)
return function(...)
if cx.res then setmime'txt' end
print(...)
end
end
outprint = print_wrapper(glue.printer(out))
local metamethods = {
__index = 1,
__newindex = 1,
__mode = 1,
}
local i64 = ffi.typeof'int64_t'
local u64 = ffi.typeof'uint64_t'
local function filter(v, k, t)
return type(v) ~= 'function'
and not (t and getmetatable(t) == t and metamethods[k])
and (type(v) ~= 'cdata'
or ffi.istype(v, i64)
or ffi.istype(v, u64))
end
outpp = print_wrapper(glue.printer(out, function(v)
return pp.format(v, ' ', {}, nil, nil, nil, true, filter)
end))
end
--sockets --------------------------------------------------------------------
function connect(host, port)
local skt = sock.tcp()
local ok, err = skt:connect(host, port)
if not ok then return nil, err end
return skt
end
--dns resolver ---------------------------------------------------------------
local resolver
function resolve(host)
resolver = resolver or require'resolver'.new{
servers = config('ns', {
'1.1.1.1', --cloudflare
'8.8.8.8', --google
}),
}
local addrs, err = resolver:lookup(host)
return addrs and addrs[1], err
end
--http requests --------------------------------------------------------------
local getpage_client
function getpage(arg1, post_data)
local opt = type(arg1) == 'table' and arg1
if not getpage_client then
local http_client = require'http_client'
getpage_client = http_client:new(update({
libs = 'sock sock_libtls zlib',
resolve = function(_, host) return resolve(host) end,
}, opt))
end
local headers = {}
if type(post_data) ~= 'string' then
post_data = json(post_data)
headers.content_type = mime_types.json
end
local u = type(arg1) == 'string' and uri.parse(arg1) or arg1.url and opt(arg1.url)
local res, req, err_class = getpage_client:request(update({
host = u and u.host,
uri = u and u.path,
https = (u and u.scheme and u.scheme or scheme()) == 'https',
method = post_data and 'POST',
headers = headers,
content = post_data,
receive_content = 'string',
debug = {protocol = true, stream = false},
--close = true,
}, opt))
if not res then
return nil, req, err_class
end
local s = res.content
local ct = res.headers['content-type']
if ct and ct.media_type == mime_types.json then
s = json_arg(s)
end
return s
end
--html encoding --------------------------------------------------------------
function html(s)
if s == nil then return '' end
return (tostring(s):gsub('[&"<>\\]', function(c)
if c == '&' then return '&'
elseif c == '"' then return '\"'
elseif c == '\\' then return '\\\\'
elseif c == '<' then return '<'
elseif c == '>' then return '>'
else return c end
end))
end
--url encoding ---------------------------------------------------------------
function url(t)
return type(t) == 'table' and uri.format(t) or t
end
function absurl(path)
path = path or ''
return config'base_url' or
scheme()..'://'..host()..
(((scheme'https' and port(443)) or
(scheme'http' and port(80))) and '' or ':'..port())..path
end
function slug(id, s)
s = glue.trim(s or '')
:gsub('[%s_;:=&@/%?]', '-') --turn separators into dashes
:gsub('%-+', '-') --compress dashes
:gsub('[^%w%-%.,~]', '') --strip chars that would be url-encoded
:lower()
assert(id >= 0)
return (s ~= '' and s..'-' or '')..tostring(id)
end
--response API ---------------------------------------------------------------
function http_error(...)
cx.req:raise(...)
end
function redirect(uri)
--TODO: make it work with relative paths
http_error{status = 303, headers = {location = uri}}
end
local function checkfunc(code, default_err)
return function(ret, err)
if ret then return ret end
http_error{
status = code,
headers = {['content-type'] = 'application/json'},
content = json{error = err or default_err},
}
end
end
checkfound = checkfunc(404, 'Not found')
checkarg = checkfunc(400, 'Invalid argument')
allow = checkfunc(403, 'Not allowed')
check500 = checkfunc(500, 'Server error')
check200 = checkfunc(200, 'OK')
function check_etag(s)
if not method'get' then return s end
if out_buffering() then return s end
local etag = xxhash.hash128(s):hex()
local etags = headers'if-none-match'
if etags and type(etags) == 'table' then
for _,t in ipairs(etags) do
if t.etag == etag then
http_error(304)
end
end
end
--send etag to client as weak etag so that gzip filter still apply.
setheader('etag', 'W/'..etag)
return s
end
function setconnectionclose()
cx.res.close = true
end
--json API -------------------------------------------------------------------
cjson.encode_sparse_array(false, 0, 0) --encode all sparse arrays
null = cjson.null
--TODO: add option to cjson to avoid this crap.
local function repl_nulls(t, null_val)
if type(t) == 'table' then
for k,v in pairs(t) do
if v == null then
v = null_val
elseif type(v) == 'table' then
repl_nulls(v, null_val)
end
end
end
return t
end
function json_arg(v, null_val)
if type(v) ~= 'string' then return v end
return repl_nulls(cjson.decode(v), null_val)
end
function json(v, indent)
if v == nil then return nil end
if indent and indent ~= '' then
return prettycjson(v, nil, indent)
else
return cjson.encode(v)
end
end
function out_json(v)
setmime'json'
outall(json(v))
end
--filesystem API -------------------------------------------------------------
do
local cache = {} --{file -> {mtime=, contents=}}
function readfile_cached(file, parse)
local cached = cache[file]
local mtime = filemtime(file)
if not mtime then --file was removed
cache[file] = nil
return nil, 'not_found'
end
local s
if not cached or cached.mtime < mtime then
s = readfile(file, parse)
cache[file] = {mtime = mtime, contents = s}
else
s = cached.contents
end
return s
end
end
function fileext(s)
return path.ext(s)
end
--make a path by combining dir and file.
function indir(dir, file)
return assert(path.combine(dir, file))
end
local function wwwdir()
return config'www_dir' or config('www_dir', config('app_name')..'-www')
end