-
Notifications
You must be signed in to change notification settings - Fork 0
/
loadimage.nim
96 lines (71 loc) · 2.08 KB
/
loadimage.nim
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
#
# nimble install https://github.com/mrhdias/fastkiss
# nim c -d:ssl -r loadimage.nim
# http://example:8080/
#
import fastkiss
import httpclient
import asyncfile
import os
from strutils import `%`
const remoteImg = "https://raw.githubusercontent.com/mrhdias/fastkiss/master/examples/test.jpg"
proc getImage(): Future[string] {.async.} =
let client = newAsyncHttpClient()
let file = openAsync(getTempDir() / "test.jpg", fmWrite)
let data = await client.getContent(remoteImg)
await file.write(data)
file.close()
return getTempDir() / "test.jpg"
proc oneshot(req: Request) {.async.} =
let filepath = await getImage()
try:
let filesize = cast[int](getFileSize(filepath))
req.response.headers["content-type"] = "image/jpeg"
req.response.headers["content-length"] = $filesize
let file = openAsync(filepath, fmRead)
let data = await file.readAll()
respond data
file.close()
removeFile(filepath)
except OSError as e:
echo "Log: $1: $2" % [e.msg, filepath]
proc parts(req: Request) {.async.} =
let filepath = await getImage()
try:
req.response.headers["content-type"] = "image/jpeg"
let filesize = cast[int](getFileSize(filepath))
let file = openAsync(filepath, fmRead)
const chunkSize = 8*1024
var remainder = filesize
while remainder > 0:
let data = await file.read(min(remainder, chunkSize))
remainder -= data.len
resp data # respond in multiple parts
file.close()
removeFile(filepath)
except OSError as e:
echo "Log: $1: $2" % [e.msg, filepath]
proc home(req: Request) {.async.} = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test</title>
</head>
<body>
Response:
<ul>
<li><a href="/oneshot">one-shot</a></li>
<li><a href="/parts">parts</a></li>
</ul>
</body>
</html>""".respond
proc main() =
let app = newApp()
app.config.port = 9000 # optional if default port
app.get("/", home)
app.get("/oneshot", oneshot)
app.get("/parts", parts)
app.run()
main()