about summary refs log tree commit diff stats
path: root/src/loader/response.nim
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2023-09-27 03:06:24 +0200
committerbptato <nincsnevem662@gmail.com>2023-09-27 03:06:24 +0200
commit14baa050d3ab4e45879582a8f87eeb1e42407909 (patch)
treeba16ced8c763e169ccf1c54f8a85a85e12e61caf /src/loader/response.nim
parentac3e737867245ac65adfa2352ce6e7fdacc57b18 (diff)
downloadchawan-14baa050d3ab4e45879582a8f87eeb1e42407909.tar.gz
Response.text: encode/decode properly
also, use blob() for images
Diffstat (limited to 'src/loader/response.nim')
-rw-r--r--src/loader/response.nim18
1 files changed, 16 insertions, 2 deletions
diff --git a/src/loader/response.nim b/src/loader/response.nim
index 8ad98f84..2be709c7 100644
--- a/src/loader/response.nim
+++ b/src/loader/response.nim
@@ -1,4 +1,5 @@
 import streams
+import unicode
 
 import bindings/quickjs
 import io/promise
@@ -10,6 +11,8 @@ import types/blob
 import types/url
 
 import chakasu/charset
+import chakasu/decoderstream
+import chakasu/encoderstream
 
 type
   Response* = ref object
@@ -62,9 +65,20 @@ proc text*(response: Response): Promise[JSResult[string]] {.jsfunc.} =
   let bodyRead = response.bodyRead
   response.bodyRead = nil
   return bodyRead.then(proc(s: string): JSResult[string] =
-    ok(s))
+    if response.charset == CHARSET_UTF_8 and s.validateUtf8() == -1:
+      ok(s)
+    else:
+      let ss = newStringStream(s)
+      let cs = if response.charset == CHARSET_UNKNOWN:
+        CHARSET_UTF_8
+      else:
+        response.charset
+      let ds = newDecoderStream(ss, cs)
+      let es = newEncoderStream(ds, CHARSET_UTF_8)
+      return ok(es.readAll())
+  )
 
-proc blob(response: Response): Promise[JSResult[Blob]] {.jsfunc.} =
+proc blob*(response: Response): Promise[JSResult[Blob]] {.jsfunc.} =
   if response.bodyRead == nil:
     let p = newPromise[JSResult[Blob]]()
     let err = JSResult[Blob]