package Minify;
use nginx;
use JavaScript::Minifier qw(minify);
 
sub handler {
  my $r=shift;
  my $cache_dir="/tmp";  # Cache directory where minified files will be kept
  my $cache_file=$r->uri;
  $cache_file=~s!/!_!g;
  $cache_file=join("/", $cache_dir, $cache_file);
  my $uri=$r->uri;
  my $filename=$r->filename;
 
  return DECLINED unless -f $filename;
 
  if (! -f $cache_file) {
    open(INFILE, $filename) or die "Error reading file: $!";
    open(OUTFILE, '>' . $cache_file ) or die "Error writting file: $!";
    minify(input => *INFILE, outfile => *OUTFILE);
    close(INFILE);
    close(OUTFILE);
  }
  $r->send_http_header("application/javascript");
  $r->sendfile($cache_file);
  return OK;
}

1;
 
__END__
