From 2463903490ad7171cf0abfaa682d1462a95fdf24 Mon Sep 17 00:00:00 2001 From: yungtravla Date: Mon, 11 Mar 2019 20:30:21 +1000 Subject: [PATCH] add JS functions gzipCompress and gzipDecompress --- modules/utils/script_builtins.go | 61 ++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/modules/utils/script_builtins.go b/modules/utils/script_builtins.go index 4c20fa42..3e4e7426 100644 --- a/modules/utils/script_builtins.go +++ b/modules/utils/script_builtins.go @@ -1,6 +1,8 @@ package utils import ( + "bytes" + "compress/gzip" "encoding/base64" "io/ioutil" @@ -157,6 +159,65 @@ func init() { return v } + // compress data with gzip + plugin.Defines["gzipCompress"] = func(call otto.FunctionCall) otto.Value { + argv := call.ArgumentList + argc := len(argv) + if argc != 1 { + return errOtto("gzipCompress: expected 1 argument, %d given instead.", argc) + } + + uncompressed_bytes := []byte( argv[0].String() ) + + var writer_buffer bytes.Buffer + gzip_writer := gzip.NewWriter(&writer_buffer) + _, err := gzip_writer.Write(uncompressed_bytes) + if err != nil { + return errOtto( "gzipCompress: could not compress data: %s", err.Error() ) + } + gzip_writer.Close() + + compressed_bytes := writer_buffer.Bytes() + + v, err := otto.ToValue( string(compressed_bytes) ) + if err != nil { + return errOtto( "Could not convert to string: %s", err.Error() ) + } + + return v + } + + // decompress data with gzip + plugin.Defines["gzipDecompress"] = func(call otto.FunctionCall) otto.Value { + argv := call.ArgumentList + argc := len(argv) + if argc != 1 { + return errOtto("gzipDecompress: expected 1 argument, %d given instead.", argc) + } + + compressed_bytes := []byte( argv[0].String() ) + reader_buffer := bytes.NewBuffer(compressed_bytes) + + gzip_reader, err := gzip.NewReader(reader_buffer) + if err != nil { + return errOtto( "gzipDecompress: could not create gzip reader: %s", err.Error() ) + } + + var decompressed_buffer bytes.Buffer + _, err = decompressed_buffer.ReadFrom(gzip_reader) + if err != nil { + return errOtto( "gzipDecompress: could not decompress data: %s", err.Error() ) + } + + decompressed_bytes := decompressed_buffer.Bytes() + v, err := otto.ToValue( string(decompressed_bytes) ) + if err != nil { + return errOtto( "Could not convert to string: %s", err.Error() ) + } + + return v + } + // read or write environment variable plugin.Defines["env"] = func(call otto.FunctionCall) otto.Value { argv := call.ArgumentList