-
-
Notifications
You must be signed in to change notification settings - Fork 409
/
req_resp_encoder.go
49 lines (42 loc) · 1.29 KB
/
req_resp_encoder.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
45
46
47
48
49
package openapi3filter
import (
"encoding/json"
"fmt"
)
func encodeBody(body interface{}, mediaType string) ([]byte, error) {
encoder, ok := bodyEncoders[mediaType]
if !ok {
return nil, &ParseError{
Kind: KindUnsupportedFormat,
Reason: fmt.Sprintf("%s %q", prefixUnsupportedCT, mediaType),
}
}
return encoder(body)
}
type BodyEncoder func(body interface{}) ([]byte, error)
var bodyEncoders = map[string]BodyEncoder{
"application/json": json.Marshal,
}
func RegisterBodyEncoder(contentType string, encoder BodyEncoder) {
if contentType == "" {
panic("contentType is empty")
}
if encoder == nil {
panic("encoder is not defined")
}
bodyEncoders[contentType] = encoder
}
// This call is not thread-safe: body encoders should not be created/destroyed by multiple goroutines.
func UnregisterBodyEncoder(contentType string) {
if contentType == "" {
panic("contentType is empty")
}
delete(bodyEncoders, contentType)
}
// RegisteredBodyEncoder returns the registered body encoder for the given content type.
//
// If no encoder was registered for the given content type, nil is returned.
// This call is not thread-safe: body encoders should not be created/destroyed by multiple goroutines.
func RegisteredBodyEncoder(contentType string) BodyEncoder {
return bodyEncoders[contentType]
}