forked from oapi-codegen/oapi-codegen
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response_handlers.go
44 lines (34 loc) · 954 Bytes
/
response_handlers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package testutil
import (
"encoding/json"
"io"
"sync"
)
func init() {
knownHandlers = make(map[string]ResponseHandler)
RegisterResponseHandler("application/json", jsonHandler)
}
var (
knownHandlersMu sync.Mutex
knownHandlers map[string]ResponseHandler
)
type ResponseHandler func(contentType string, raw io.Reader, obj interface{}, strict bool) error
func RegisterResponseHandler(mime string, handler ResponseHandler) {
knownHandlersMu.Lock()
defer knownHandlersMu.Unlock()
knownHandlers[mime] = handler
}
func getHandler(mime string) ResponseHandler {
knownHandlersMu.Lock()
defer knownHandlersMu.Unlock()
return knownHandlers[mime]
}
// This function assumes that the response contains JSON and unmarshals it
// into the specified object.
func jsonHandler(_ string, r io.Reader, obj interface{}, strict bool) error {
d := json.NewDecoder(r)
if strict {
d.DisallowUnknownFields()
}
return json.NewDecoder(r).Decode(obj)
}