-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoding.go
50 lines (41 loc) · 992 Bytes
/
encoding.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
50
package expose
import (
"encoding/json"
"io"
)
// Encoding is used for content negotiating. Request arguments and response values are encoded and decoded
// with the encoding that is matching the `Content-Type` or `Accept` header.
type Encoding struct {
MimeType string
GetDecoder func(r io.Reader) Decoder
GetEncoder func(w io.Writer) Encoder
}
type Decoder interface {
Decode(v any) error
}
type DecoderFunc func(v any) error
func (f DecoderFunc) Decode(v any) error {
return f(v)
}
type Encoder interface {
Encode(v any) error
}
type EncoderFunc func(v any) error
func (f EncoderFunc) Encode(v any) error {
return f(v)
}
var JsonEncoding = Encoding{
MimeType: "application/json",
GetEncoder: func(w io.Writer) Encoder {
enc := json.NewEncoder(w)
return EncoderFunc(func(v any) error {
return enc.Encode(v)
})
},
GetDecoder: func(r io.Reader) Decoder {
dec := json.NewDecoder(r)
return DecoderFunc(func(v any) error {
return dec.Decode(v)
})
},
}