encode.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2020 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package caches
  5. import (
  6. "bytes"
  7. "crypto/md5"
  8. "encoding/gob"
  9. "encoding/json"
  10. "fmt"
  11. "io"
  12. )
  13. // md5 hash string
  14. func Md5(str string) string {
  15. m := md5.New()
  16. io.WriteString(m, str)
  17. return fmt.Sprintf("%x", m.Sum(nil))
  18. }
  19. func Encode(data interface{}) ([]byte, error) {
  20. //return JsonEncode(data)
  21. return GobEncode(data)
  22. }
  23. func Decode(data []byte, to interface{}) error {
  24. //return JsonDecode(data, to)
  25. return GobDecode(data, to)
  26. }
  27. func GobEncode(data interface{}) ([]byte, error) {
  28. var buf bytes.Buffer
  29. enc := gob.NewEncoder(&buf)
  30. err := enc.Encode(&data)
  31. if err != nil {
  32. return nil, err
  33. }
  34. return buf.Bytes(), nil
  35. }
  36. func GobDecode(data []byte, to interface{}) error {
  37. buf := bytes.NewBuffer(data)
  38. dec := gob.NewDecoder(buf)
  39. return dec.Decode(to)
  40. }
  41. func JsonEncode(data interface{}) ([]byte, error) {
  42. val, err := json.Marshal(data)
  43. if err != nil {
  44. return nil, err
  45. }
  46. return val, nil
  47. }
  48. func JsonDecode(data []byte, to interface{}) error {
  49. return json.Unmarshal(data, to)
  50. }