| 1 | package js |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "compress/gzip" |
| 6 | "encoding/base64" |
| 7 | |
| 8 | "github.com/robertkrimen/otto" |
| 9 | ) |
| 10 | |
| 11 | func btoa(call otto.FunctionCall) otto.Value { |
| 12 | varValue := base64.StdEncoding.EncodeToString([]byte(call.Argument(0).String())) |
| 13 | v, err := otto.ToValue(varValue) |
| 14 | if err != nil { |
| 15 | return ReportError("Could not convert to string: %s", varValue) |
| 16 | } |
| 17 | |
| 18 | return v |
| 19 | } |
| 20 | |
| 21 | func atob(call otto.FunctionCall) otto.Value { |
| 22 | varValue, err := base64.StdEncoding.DecodeString(call.Argument(0).String()) |
| 23 | if err != nil { |
| 24 | return ReportError("Could not decode string: %s", call.Argument(0).String()) |
| 25 | } |
| 26 | |
| 27 | v, err := otto.ToValue(string(varValue)) |
| 28 | if err != nil { |
| 29 | return ReportError("Could not convert to string: %s", varValue) |
| 30 | } |
| 31 | |
| 32 | return v |
| 33 | } |
| 34 | |
| 35 | func gzipCompress(call otto.FunctionCall) otto.Value { |
| 36 | argv := call.ArgumentList |
| 37 | argc := len(argv) |
| 38 | if argc != 1 { |
| 39 | return ReportError("gzipCompress: expected 1 argument, %d given instead.", argc) |
| 40 | } |
| 41 | |
| 42 | uncompressedBytes := []byte(argv[0].String()) |
| 43 | |
| 44 | var writerBuffer bytes.Buffer |
| 45 | gzipWriter := gzip.NewWriter(&writerBuffer) |
| 46 | _, err := gzipWriter.Write(uncompressedBytes) |
| 47 | if err != nil { |
| 48 | return ReportError("gzipCompress: could not compress data: %s", err.Error()) |
| 49 | } |
| 50 | gzipWriter.Close() |
| 51 | |
| 52 | compressedBytes := writerBuffer.Bytes() |
| 53 | |
| 54 | v, err := otto.ToValue(string(compressedBytes)) |
| 55 | if err != nil { |
| 56 | return ReportError("Could not convert to string: %s", err.Error()) |
| 57 | } |
| 58 | |
| 59 | return v |
| 60 | } |
| 61 | |
| 62 | func gzipDecompress(call otto.FunctionCall) otto.Value { |
| 63 | argv := call.ArgumentList |
| 64 | argc := len(argv) |
| 65 | if argc != 1 { |
| 66 | return ReportError("gzipDecompress: expected 1 argument, %d given instead.", argc) |
| 67 | } |
| 68 | |
| 69 | compressedBytes := []byte(argv[0].String()) |
| 70 | readerBuffer := bytes.NewBuffer(compressedBytes) |
| 71 | |
| 72 | gzipReader, err := gzip.NewReader(readerBuffer) |
| 73 | if err != nil { |
| 74 | return ReportError("gzipDecompress: could not create gzip reader: %s", err.Error()) |
| 75 | } |
| 76 | |
| 77 | var decompressedBuffer bytes.Buffer |
| 78 | _, err = decompressedBuffer.ReadFrom(gzipReader) |
| 79 | if err != nil { |
| 80 | return ReportError("gzipDecompress: could not decompress data: %s", err.Error()) |
| 81 | } |
| 82 | |
| 83 | decompressedBytes := decompressedBuffer.Bytes() |
| 84 | v, err := otto.ToValue(string(decompressedBytes)) |
| 85 | if err != nil { |
| 86 | return ReportError("Could not convert to string: %s", err.Error()) |
| 87 | } |
| 88 | |
| 89 | return v |
| 90 | } |