encdec.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package simplemaria
  2. import (
  3. "bytes"
  4. "compress/flate"
  5. "encoding/hex"
  6. "io/ioutil"
  7. )
  8. // MariaDB/MySQL does not handle some characters well.
  9. // Compressing and hex encoding the value is one of many possible ways
  10. // to avoid this. Using BLOB fields and different datatypes is another.
  11. func Encode(value *string) error {
  12. // Don't encode empty strings
  13. if *value == "" {
  14. return nil
  15. }
  16. var buf bytes.Buffer
  17. compressorWriter, err := flate.NewWriter(&buf, 1) // compression level 1 (fastest)
  18. if err != nil {
  19. return err
  20. }
  21. compressorWriter.Write([]byte(*value))
  22. compressorWriter.Close()
  23. *value = hex.EncodeToString(buf.Bytes())
  24. return nil
  25. }
  26. // Dehex and decompress the given string
  27. func Decode(code *string) error {
  28. // Don't decode empty strings
  29. if *code == "" {
  30. return nil
  31. }
  32. unhexedBytes, err := hex.DecodeString(*code)
  33. if err != nil {
  34. return err
  35. }
  36. buf := bytes.NewBuffer(unhexedBytes)
  37. decompressorReader := flate.NewReader(buf)
  38. decompressedBytes, err := ioutil.ReadAll(decompressorReader)
  39. decompressorReader.Close()
  40. if err != nil {
  41. return err
  42. }
  43. *code = string(decompressedBytes)
  44. return nil
  45. }