about summary refs log tree commit diff stats
path: root/src/io
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2023-05-11 18:13:38 +0200
committerbptato <nincsnevem662@gmail.com>2023-05-11 18:13:38 +0200
commit34b90a0b40fbb624655a2ff8624e89101d71299b (patch)
tree372a790b769ce968afd2035b96de1679a65116e6 /src/io
parent87f9bd656b2a8a8d4ebd029ba6a78f1dc93558eb (diff)
downloadchawan-34b90a0b40fbb624655a2ff8624e89101d71299b.tar.gz
Fix some fetch crashes
Now it should work for very basic use-cases
Diffstat (limited to 'src/io')
-rw-r--r--src/io/loader.nim6
-rw-r--r--src/io/request.nim22
2 files changed, 15 insertions, 13 deletions
diff --git a/src/io/loader.nim b/src/io/loader.nim
index 15b8e3e2..33b3977f 100644
--- a/src/io/loader.nim
+++ b/src/io/loader.nim
@@ -243,6 +243,7 @@ proc fetch*(loader: FileLoader, input: Request): Promise[Response] =
     request: input,
     stream: stream
   )
+  return promise
 
 proc newResponse(res: int, request: Request, stream: Stream = nil): Response =
   return Response(
@@ -260,7 +261,10 @@ proc onConnected*(loader: FileLoader, fd: int) =
   stream.sread(res)
   if res == 0:
     let response = newResponse(res, request, stream)
-    response.unregisterFun = proc() = loader.unregisterFun(fd)
+    assert loader.unregisterFun != nil
+    response.unregisterFun = proc() =
+      loader.ongoing.del(fd)
+      loader.unregisterFun(fd)
     stream.sread(response.status)
     stream.sread(response.headers)
     applyHeaders(request, response)
diff --git a/src/io/request.nim b/src/io/request.nim
index ce42c61b..3cb277a9 100644
--- a/src/io/request.nim
+++ b/src/io/request.nim
@@ -211,13 +211,19 @@ func getOrDefault*(headers: HeaderList, k: string, default = ""): string =
   else:
     default
 
-proc text*(response: Response): string {.jsfunc.} =
-  #TODO: this looks pretty unsafe.
-  result = response.body.readAll()
-  response.body.close()
+#TODO: this should be a property of body
+proc close*(response: Response) {.jsfunc.} =
   response.bodyUsed = true
   if response.unregisterFun != nil:
     response.unregisterFun()
+  if response.body != nil:
+    response.body.close()
+
+proc text*(response: Response): string {.jsfunc.} =
+  if response.body == nil:
+    return ""
+  result = response.body.readAll()
+  response.close()
 
 #TODO: get rid of this
 proc readAll*(response: Response): string {.jsfunc.} =
@@ -231,14 +237,6 @@ proc Response_json*(ctx: JSContext, this: JSValue, argc: cint, argv: ptr JSValue
   var s = response.text()
   return JS_ParseJSON(ctx, addr s[0], cast[csize_t](s.len), cstring"<input>")
 
-#TODO: this should be a property of body
-proc close*(response: Response) {.jsfunc.} =
-  #TODO: this looks pretty unsafe
-  response.body.close()
-  response.bodyUsed = true
-  if response.unregisterFun != nil:
-    response.unregisterFun()
-
 func credentialsMode*(attribute: CORSAttribute): CredentialsMode =
   case attribute
   of NO_CORS, ANONYMOUS: