commands: Return a reader in a Response#Reader method, instead of making Response implementing io.Reader
Matt Bell committed
Nov 3, 2014 at 16:30 UTC
f6c38882f0a405defb99105f714bee3655783153
2 files changed
+20
-16
commands/http/handler.go
+4
-1
@@ -56,10 +56,13 @@ func (i Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
56
}
57
}
58
59
- _, err = io.Copy(w, res)
59
+ out, err := res.Reader()
60
if err != nil {
61
w.WriteHeader(http.StatusInternalServerError)
62
w.Header().Set("Content-Type", "text/plain")
63
w.Write([]byte(err.Error()))
64
+ return
65
}
66
+
67
+ io.Copy(w, out)
68
}
commands/response.go
+16
-15
@@ -74,8 +74,6 @@ var marshallers = map[EncodingType]Marshaller{
74
// Response is the result of a command request. Handlers write to the response,
75
// setting Error or Value. Response is returned to the client.
76
type Response interface {
77
- io.Reader
78
-
77
Request() Request
78
79
// Set/Return the response Error
@@ -89,6 +87,9 @@ type Response interface {
87
// Marshal marshals out the response into a buffer. It uses the EncodingType
88
// on the Request to chose a Marshaller (Codec).
89
Marshal() ([]byte, error)
90
+
91
+ // Gets a io.Reader that reads the marshalled output
92
+ Reader() (io.Reader, error)
93
}
94
95
type response struct {
@@ -137,28 +138,28 @@ func (r *response) Marshal() ([]byte, error) {
138
return marshaller(r)
139
}
140
140
-func (r *response) Read(p []byte) (int, error) {
141
- // if command set value to a io.Reader, set that as our output stream
141
+// Reader returns an `io.Reader` representing marshalled output of this Response
142
+// Note that multiple calls to this will return a reference to the same io.Reader
143
+func (r *response) Reader() (io.Reader, error) {
144
+ // if command set value to a io.Reader, use that as our reader
145
if r.out == nil {
146
if out, ok := r.value.(io.Reader); ok {
147
r.out = out
148
}
149
}
150
148
- // if there is an output stream set, read from it
149
- if r.out != nil {
150
- return r.out.Read(p)
151
- }
151
+ if r.out == nil {
152
+ // no reader set, so marshal the error or value
153
+ marshalled, err := r.Marshal()
154
+ if err != nil {
155
+ return nil, err
156
+ }
157
153
- // no stream set, so marshal the error or value
154
- output, err := r.Marshal()
155
- if err != nil {
156
- return 0, err
158
+ // create a Reader from the marshalled data
159
+ r.out = bytes.NewReader(marshalled)
160
}
161
159
- // then create a Reader from the marshalled data, and use it as our output stream
160
- r.out = bytes.NewReader(output)
161
- return r.out.Read(p)
162
+ return r.out, nil
163
}
164
165
// NewResponse returns a response to match given Request