data.go 2.2 KB

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