utils.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2013 Beego Authors
  2. // Copyright 2014 The Macaron Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  5. // not use this file except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. package session
  16. import (
  17. "bytes"
  18. "crypto/rand"
  19. "encoding/gob"
  20. "io"
  21. "github.com/Unknwon/com"
  22. )
  23. func init() {
  24. gob.Register([]interface{}{})
  25. gob.Register(map[int]interface{}{})
  26. gob.Register(map[string]interface{}{})
  27. gob.Register(map[interface{}]interface{}{})
  28. gob.Register(map[string]string{})
  29. gob.Register(map[int]string{})
  30. gob.Register(map[int]int{})
  31. gob.Register(map[int]int64{})
  32. }
  33. func EncodeGob(obj map[interface{}]interface{}) ([]byte, error) {
  34. for _, v := range obj {
  35. gob.Register(v)
  36. }
  37. buf := bytes.NewBuffer(nil)
  38. err := gob.NewEncoder(buf).Encode(obj)
  39. return buf.Bytes(), err
  40. }
  41. func DecodeGob(encoded []byte) (out map[interface{}]interface{}, err error) {
  42. buf := bytes.NewBuffer(encoded)
  43. err = gob.NewDecoder(buf).Decode(&out)
  44. return out, err
  45. }
  46. // generateRandomKey creates a random key with the given strength.
  47. func generateRandomKey(strength int) []byte {
  48. k := make([]byte, strength)
  49. if n, err := io.ReadFull(rand.Reader, k); n != strength || err != nil {
  50. return com.RandomCreateBytes(strength)
  51. }
  52. return k
  53. }