creationix / seaduk

An implementation of nucleus-js using duktape and libuv implemented in C
Other
34 stars 5 forks source link

Sample HTTP server #5

Open creationix opened 8 years ago

creationix commented 8 years ago

I ported http-codec from luvit to seaduk and made a minimal HTTP server using this and wrap-socket.

https://github.com/nucleus-js/seaduk/blob/master/test-app/http-server.js

// Load the libraries
var httpCodec = require('deps/http-codec');
var createServer = require("deps/net").createServer;
var uv = require('uv');

// Create a TCP server using HTTP codec as the decoder/encoder
var server = createServer({
  port: 8080,
  encode: httpCodec.encoder(),
  decode: httpCodec.decoder(),
}, function (client) {
  // Read all parsed HTTP messages from the stream
  client.read(onRead);
  function onRead(err, data) {
    if (err) throw err;
    if (data) return client.read(onRead);
    // When we get an empty stream, that means a full request with body has been parsed
    if (data === "") {
      // Let's send a response head
      client.write({
        code: 200,
        headers: [
          "Server", "seaduk",
          "Date", new Date().toUTCString(),
          "Connection", "close",
          "Content-Length", "12",
          "Content-Type", "text/plain",
        ]
      });
      // And response body
      client.write("Hello World\n");
      // And shutdown the stream
      client.write(null, function (err) {
        if (err) throw err;
        print("Closing server");
        server.close();
      });
    }
  }
});
creationix commented 8 years ago

Next step is either to prototype a higher-level HTTP library or implement websockets + msgpack + super-agent-rpc.

creationix commented 8 years ago

Ideas for HTTP library API: