File: req_resp_encoder.go

package info (click to toggle)
golang-github-getkin-kin-openapi 0.124.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,288 kB
  • sloc: sh: 344; makefile: 4
file content (58 lines) | stat: -rw-r--r-- 1,528 bytes parent folder | download
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
50
51
52
53
54
55
56
57
58
package openapi3filter

import (
	"encoding/json"
	"fmt"
	"sync"
)

func encodeBody(body interface{}, mediaType string) ([]byte, error) {
	if encoder := RegisteredBodyEncoder(mediaType); encoder != nil {
		return encoder(body)
	}
	return nil, &ParseError{
		Kind:   KindUnsupportedFormat,
		Reason: fmt.Sprintf("%s %q", prefixUnsupportedCT, mediaType),
	}
}

// BodyEncoder really is an (encoding/json).Marshaler
type BodyEncoder func(body interface{}) ([]byte, error)

var bodyEncodersM sync.RWMutex
var bodyEncoders = map[string]BodyEncoder{
	"application/json": json.Marshal,
}

// RegisterBodyEncoder enables package-wide decoding of contentType values
func RegisterBodyEncoder(contentType string, encoder BodyEncoder) {
	if contentType == "" {
		panic("contentType is empty")
	}
	if encoder == nil {
		panic("encoder is not defined")
	}
	bodyEncodersM.Lock()
	bodyEncoders[contentType] = encoder
	bodyEncodersM.Unlock()
}

// UnregisterBodyEncoder disables package-wide decoding of contentType values
func UnregisterBodyEncoder(contentType string) {
	if contentType == "" {
		panic("contentType is empty")
	}
	bodyEncodersM.Lock()
	delete(bodyEncoders, contentType)
	bodyEncodersM.Unlock()
}

// RegisteredBodyEncoder returns the registered body encoder for the given content type.
//
// If no encoder was registered for the given content type, nil is returned.
func RegisteredBodyEncoder(contentType string) BodyEncoder {
	bodyEncodersM.RLock()
	mayBE := bodyEncoders[contentType]
	bodyEncodersM.RUnlock()
	return mayBE
}