Преглед на файлове

Experimental support for duktape (Step 4/?)

bel преди 9 години
родител
ревизия
4ab1e763ac
променени са 2 файла, в които са добавени 40 реда и са изтрити 11 реда
  1. 36 11
      src/mod_duktape.inl
  2. 4 0
      test/prime.ssjs

+ 36 - 11
src/mod_duktape.inl

@@ -5,28 +5,53 @@
 
 #include "duktape.h"
 
-/* TODO: This stub is currently not useful, since there is no way to communicate
- * with the client. */
-static void mg_exec_lua_script(struct mg_connection *conn, const char *path)
+/* TODO: Malloc function should use mg_malloc/mg_free */
+
+/* TODO: the mg context should be added to duktape as well */
+/* Alternative: redefine a new, clean API from scratch (instead of using mg),
+ * or at least do not add problematic functions. */
+/* Note: This is only experimental support, so any API may still change. */
+
+
+/* TODO: use upvalues (or whatever equivalent) */
+static struct mg_connection *xxx_conn = NULL;
+
+static duk_ret_t duk_itf_send(duk_context *ctx)
+{
+	duk_size_t len = 0;
+	const char *val = duk_require_lstring(ctx, -1, &len);
+
+	mg_write(xxx_conn, val, len);
+
+	duk_push_true(ctx);
+	return 1;
+}
+
+
+static void mg_exec_duktape_script(struct mg_connection *conn, const char *path)
 {
 	duk_context *ctx = NULL;
 
-#ifdef WIN32
-	(void)MakeConsole();
-#endif
+	conn->must_close = 1;
 
 	ctx = duk_create_heap_default();
 	if (!ctx) {
-		fprintf(stderr, "Failed to create a Duktape heap.\n");
-		goto finished;
+		mg_cry(conn, "Failed to create a Duktape heap.");
+		goto exec_duktape_finished;
 	}
 
+	duk_push_global_object(ctx);
+	duk_push_c_function(ctx, duk_itf_send, 1 /*nargs*/);
+	duk_put_prop_string(ctx, -2, "send");
+
+	xxx_conn = conn;
+
 	if (duk_peval_file(ctx, path) != 0) {
-		fprintf(stderr, "%s\n", duk_safe_to_string(ctx, -1));
-		goto finished;
+		mg_cry(conn, "%s", duk_safe_to_string(ctx, -1));
+		goto exec_duktape_finished;
 	}
 	duk_pop(ctx); /* ignore result */
 
-finished:
+exec_duktape_finished:
 	duk_destroy_heap(ctx);
 }

+ 4 - 0
test/prime.js → test/prime.ssjs

@@ -29,4 +29,8 @@ function primeTest() {
     print(res.join(' '));
 }
 
+print = this.send || print
+
+print('HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n');
+
 primeTest();