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