-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdecoder.go
More file actions
72 lines (57 loc) · 1.84 KB
/
decoder.go
File metadata and controls
72 lines (57 loc) · 1.84 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package courier
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
)
// DecoderFunc is used to create a Decoder from io.Reader stream
// of message bytes before calling MessageHandler;
// the context.Context value may be used to select appropriate Decoder.
type DecoderFunc func(context.Context, io.Reader) Decoder
// Decoder helps to decode message bytes into the desired object
type Decoder interface {
// Decode decodes message bytes into the passed object
Decode(v interface{}) error
}
// DefaultDecoderFunc is a DecoderFunc that uses a json.Decoder as the Decoder.
func DefaultDecoderFunc(_ context.Context, r io.Reader) Decoder {
return json.NewDecoder(r)
}
func base64JsonDecoder(_ context.Context, r io.Reader) Decoder {
return json.NewDecoder(base64.NewDecoder(base64.StdEncoding, r))
}
// ChainDecoderFunc creates a DecoderFunc that tries multiple decoders in sequence.
// It attempts each decoder in order; if successful, it stops. If all fail, it returns
// a combined error containing all individual errors.
func ChainDecoderFunc(decoders ...DecoderFunc) DecoderFunc {
return func(ctx context.Context, r io.Reader) Decoder {
buf := new(bytes.Buffer)
if _, err := buf.ReadFrom(r); err != nil {
return &chainDecoder{decoders: nil}
}
decs := make([]Decoder, 0, len(decoders))
for _, fn := range decoders {
decs = append(decs, fn(ctx, bytes.NewReader(buf.Bytes())))
}
return &chainDecoder{decoders: decs}
}
}
type chainDecoder struct {
decoders []Decoder
}
func (f *chainDecoder) Decode(v interface{}) error {
var errs []error
for _, dec := range f.decoders {
if err := dec.Decode(v); err != nil {
errs = append(errs, err)
continue
}
return nil
}
return fmt.Errorf("all decoders failed: %w", errors.Join(errs...))
}
func (f DecoderFunc) apply(o *clientOptions) { o.newDecoder = f }