File: req_resp_encoder.go

package info (click to toggle)
golang-github-getkin-kin-openapi 0.110.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,932 kB
  • sloc: makefile: 3
file content (49 lines) | stat: -rw-r--r-- 1,319 bytes parent folder | download | duplicates (2)
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]
}