transcoding.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package sessions
  2. import "encoding/json"
  3. type (
  4. // Marshaler is the common marshaler interface, used by transcoder.
  5. Marshaler interface {
  6. Marshal(interface{}) ([]byte, error)
  7. }
  8. // Unmarshaler is the common unmarshaler interface, used by transcoder.
  9. Unmarshaler interface {
  10. Unmarshal([]byte, interface{}) error
  11. }
  12. // Transcoder is the interface that transcoders should implement, it includes just the `Marshaler` and the `Unmarshaler`.
  13. Transcoder interface {
  14. Marshaler
  15. Unmarshaler
  16. }
  17. )
  18. // DefaultTranscoder is the default transcoder across databases, it's the JSON by default.
  19. // Change it if you want a different serialization/deserialization inside your session databases (when `UseDatabase` is used).
  20. var DefaultTranscoder Transcoder = defaultTranscoder{}
  21. type defaultTranscoder struct{}
  22. func (d defaultTranscoder) Marshal(value interface{}) ([]byte, error) {
  23. if tr, ok := value.(Marshaler); ok {
  24. return tr.Marshal(value)
  25. }
  26. if jsonM, ok := value.(json.Marshaler); ok {
  27. return jsonM.MarshalJSON()
  28. }
  29. return json.Marshal(value)
  30. }
  31. func (d defaultTranscoder) Unmarshal(b []byte, outPtr interface{}) error {
  32. if tr, ok := outPtr.(Unmarshaler); ok {
  33. return tr.Unmarshal(b, outPtr)
  34. }
  35. if jsonUM, ok := outPtr.(json.Unmarshaler); ok {
  36. return jsonUM.UnmarshalJSON(b)
  37. }
  38. return json.Unmarshal(b, outPtr)
  39. }