dartist / express

A thin express-js inspired layer around Dart's primitive HttpServer APIs
Other
126 stars 11 forks source link

Enable GZIP compress in Express #23

Closed agreatfool closed 9 years ago

agreatfool commented 9 years ago

I searched several posts. Seems it's possible to enable GZIP in HttpServer class.

   /**
   * Whether the [HttpServer] should compress the content, if possible.
   *
   * The content can only be compressed when the response is using
   * chunked Transfer-Encoding and the incoming request has `gzip`
   * as an accepted encoding in the Accept-Encoding header.
   *
   * The default value is `false` (compression disabled).
   * To enable, set `autoCompress` to `true`.
   */
  bool autoCompress;
HttpServer server;
...
server.autoCompress = true;

This could be done in _Express:listen(). Or expose an API to enable the switch by user.

mythz commented 9 years ago

You should be able to set HttpServer configuration on the response of listen(), e.g:

var app = new Express();
//.. configure express
app.listen("127.0.0.1", 8000)
    .then((HttpServer x) {
        x.autoCompress = true;
    });
agreatfool commented 9 years ago

I tried, and found an error:

  app.listen('127.0.0.1', setting['port']).then((HttpServer server) {
    server.autoCompress = true;
  });
Unhandled exception:
Uncaught Error: The null object does not have a setter 'autoCompress='.

NoSuchMethodError: method not found: 'autoCompress='
Receiver: null
Arguments: [true]

I guess it shall be the issue of these codes:

Class _Express
  Future<HttpServer> listen([String host="127.0.0.1", int port=80]){
    return HttpServer.bind(host, port).then((HttpServer x) {
      server = x;
      ...
mythz commented 9 years ago

oh right, it looks like it's not getting returned in the future callback. Looking at the code you should be able to do:

var app = new Express();
//.. configure express
app.listen("127.0.0.1", 8000)
   .then(() {
       app.server.autoCompress = true;
   });
agreatfool commented 9 years ago

Cool! I tested it, it works:

Jonathan-MBP:Prog Jonathan$ curl --request POST http://cart.com/api/init --silent --write-out "%{size_download}\n" --output /dev/null
1481
Jonathan-MBP:Prog Jonathan$ curl --request POST http://cart.com/api/init --silent -H "Accept-Encoding: gzip,deflate" --write-out "%{size_download}\n" --output /dev/null
591

Thank you very much.