Sha256: 6bdab82d76666a7678246ec9c71dc2586d24ca9e9d419ab7532dcd5206cb1fbf

Contents?: true

Size: 1.02 KB

Versions: 4

Compression:

Stored size: 1.02 KB

Contents

# run with:
#
#   bundle exec ./bin/opal ./doc/examples/node_http_server.rb
#

%x{
  var http;
  http = require('http');
}


module HTTP
  class Server
    %x{
      var dom_class = http.Server;
      #{self}['_proto'] = dom_class.prototype;
      def = #{self}._proto;
      dom_class.prototype._klass = #{self};
    }

    def self.__http__
      Native(`http`)
    end

    alias_native :listen, :listen

    def self.start options = {}, &block
      host = options[:host] || '127.0.0.1'
      port = options[:port] || 3000

      server = __http__.createServer do |req, res|
        req = Native(req)
        res = Native(res)
        status, headers, body = block.call(`req`)
        res.writeHead(status, headers.to_n);
        res.end(body.join(' '));
      end

      server.listen(port, host)
      puts("Server running at http://#{host}:#{port}/");
      server
    end
  end
end

util = Native(`require('util')`)
HTTP::Server.start port: 3000 do |env|
  [200, {'Content-Type' => 'text/plain'}, ["Hello World!\n", util.inspect(env)]]
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
opal-0.5.5 doc/examples/node_http_server.rb
opal-0.5.4 doc/examples/node_http_server.rb
opal-0.5.2 doc/examples/node_http_server.rb
opal-0.5.0 doc/examples/node_http_server.rb