commands: Added plaintext marshalling to Response#Marshal()
Matt Bell committed
Oct 28, 2014 at 19:29 UTC
b54801cc10f5db24ad5615e213b6672d98570327
1 file changed
+27
-7
commands/response.go
+27
-7
@@ -36,16 +36,39 @@ type EncodingType string
36
const (
37
JSON = "json"
38
XML = "xml"
39
+ Text = "text"
40
// TODO: support more encoding types
41
)
42
43
// Marshaller is a function used by coding types.
44
// TODO this should just be a `coding.Codec`
44
-type Marshaller func(v interface{}) ([]byte, error)
45
+type Marshaller func(res Response) ([]byte, error)
46
47
var marshallers = map[EncodingType]Marshaller{
47
- JSON: json.Marshal,
48
- XML: xml.Marshal,
48
+ JSON: func(res Response) ([]byte, error) {
49
+ if res.Error() != nil {
50
+ return json.Marshal(res.Error())
51
+ }
52
+ return json.Marshal(res.Value())
53
+ },
54
+ XML: func(res Response) ([]byte, error) {
55
+ if res.Error() != nil {
56
+ return xml.Marshal(res.Error())
57
+ }
58
+ return xml.Marshal(res.Value())
59
+ },
60
+ Text: func(res Response) ([]byte, error) {
61
+ format := res.Request().Command().Format
62
+ if format == nil {
63
+ return nil, ErrNoFormatter
64
+ }
65
+
66
+ s, err := format(res)
67
+ if err != nil {
68
+ return nil, err
69
+ }
70
+ return []byte(s), nil
71
+ },
72
}
73
74
// Response is the result of a command request. Handlers write to the response,
@@ -111,10 +134,7 @@ func (r *response) Marshal() ([]byte, error) {
134
return nil, fmt.Errorf("No marshaller found for encoding type '%s'", enc)
135
}
136
114
- if r.err != nil {
115
- return marshaller(r.err)
116
- }
117
- return marshaller(r.value)
137
+ return marshaller(r)
138
}
139
140
func (r *response) Read(p []byte) (int, error) {