marshaler_struct_test.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package test
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "strings"
  7. )
  8. type structMarshaler struct {
  9. X string
  10. }
  11. func (m structMarshaler) encode(str string) string {
  12. buf := bytes.Buffer{}
  13. b64 := base64.NewEncoder(base64.StdEncoding, &buf)
  14. if _, err := b64.Write([]byte(str)); err != nil {
  15. panic(err)
  16. }
  17. if err := b64.Close(); err != nil {
  18. panic(err)
  19. }
  20. return buf.String()
  21. }
  22. func (m structMarshaler) decode(str string) string {
  23. if len(str) == 0 {
  24. return ""
  25. }
  26. b64 := base64.NewDecoder(base64.StdEncoding, strings.NewReader(str))
  27. bs := make([]byte, len(str))
  28. if n, err := b64.Read(bs); err != nil {
  29. panic(err)
  30. } else {
  31. bs = bs[:n]
  32. }
  33. return string(bs)
  34. }
  35. func (m structMarshaler) MarshalJSON() ([]byte, error) {
  36. return []byte(`"MANUAL__` + m.encode(m.X) + `"`), nil
  37. }
  38. func (m *structMarshaler) UnmarshalJSON(text []byte) error {
  39. m.X = m.decode(strings.TrimPrefix(strings.Trim(string(text), `"`), "MANUAL__"))
  40. return nil
  41. }
  42. var _ json.Marshaler = structMarshaler{}
  43. var _ json.Unmarshaler = &structMarshaler{}
  44. type structMarshalerAlias structMarshaler
  45. func init() {
  46. testCases = append(testCases,
  47. (*structMarshaler)(nil),
  48. (*structMarshalerAlias)(nil),
  49. (*struct {
  50. S string
  51. M structMarshaler
  52. I int8
  53. })(nil),
  54. (*struct {
  55. S string
  56. M structMarshalerAlias
  57. I int8
  58. })(nil),
  59. )
  60. }