Skip to content

Commit 66e1d1b

Browse files
yangzh-deepmapdeepmap-marcinr
authored andcommitted
Add support for proto in testutil.CompletedRequest, for testing proto… (#103)
* Add support for proto in testutil.CompletedRequest, for testing proto-related message request/resp. * Use a handler registry to allow user register custom response handlers. * Cleanup Go modules. * Use generic io.Reader, to allow more flexibiltiy. pass in complete content-type so that user can have more flexibility.
1 parent cca860b commit 66e1d1b

File tree

2 files changed

+46
-6
lines changed

2 files changed

+46
-6
lines changed

request_helpers.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -167,13 +167,13 @@ func (c *CompletedRequest) UnmarshalBodyToObject(obj interface{}) error {
167167

168168
// Content type can have an annotation after ;
169169
contentParts := strings.Split(ctype, ";")
170-
171-
switch strings.TrimSpace(contentParts[0]) {
172-
case "application/json":
173-
return json.Unmarshal(c.Recorder.Body.Bytes(), obj)
174-
default:
175-
return fmt.Errorf("no Content-Type on response")
170+
content := strings.TrimSpace(contentParts[0])
171+
handler := getHandler(content)
172+
if handler == nil {
173+
return fmt.Errorf("unhandled content: %s", content)
176174
}
175+
176+
return handler(ctype, c.Recorder.Body, obj)
177177
}
178178

179179
// This function assumes that the response contains JSON and unmarshals it

response_handlers.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package testutil
2+
3+
import (
4+
"encoding/json"
5+
"io"
6+
"sync"
7+
)
8+
9+
func init() {
10+
knownHandlers = make(map[string]ResponseHandler)
11+
12+
RegisterResponseHandler("application/json", jsonHandler)
13+
}
14+
15+
var (
16+
knownHandlersMu sync.Mutex
17+
knownHandlers map[string]ResponseHandler
18+
)
19+
20+
type ResponseHandler func(contentType string, raw io.Reader, obj interface{}) error
21+
22+
func RegisterResponseHandler(mime string, handler ResponseHandler) {
23+
knownHandlersMu.Lock()
24+
defer knownHandlersMu.Unlock()
25+
26+
knownHandlers[mime] = handler
27+
}
28+
29+
func getHandler(mime string) ResponseHandler {
30+
knownHandlersMu.Lock()
31+
defer knownHandlersMu.Unlock()
32+
33+
return knownHandlers[mime]
34+
}
35+
36+
// This function assumes that the response contains JSON and unmarshals it
37+
// into the specified object.
38+
func jsonHandler(_ string, r io.Reader, obj interface{}) error {
39+
return json.NewDecoder(r).Decode(obj)
40+
}

0 commit comments

Comments
 (0)