-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary.go
42 lines (34 loc) · 894 Bytes
/
binary.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
package render
import (
"encoding"
"fmt"
"io"
)
// Binary can render values which implment the encoding.BinaryMarshaler
// interface.
type Binary struct{}
var (
_ Handler = (*Binary)(nil)
_ FormatsHandler = (*Binary)(nil)
)
// Render writes result of calling MarshalBinary() on v. If v does not implment
// encoding.BinaryMarshaler the ErrCannotRander error will be returned.
func (br *Binary) Render(w io.Writer, v any) error {
x, ok := v.(encoding.BinaryMarshaler)
if !ok {
return fmt.Errorf("%w: %T", ErrCannotRender, v)
}
b, err := x.MarshalBinary()
if err != nil {
return fmt.Errorf("%w: %w", ErrFailed, err)
}
_, err = w.Write(b)
if err != nil {
return fmt.Errorf("%w: %w", ErrFailed, err)
}
return nil
}
// Formats returns a list of format strings that this Handler supports.
func (br *Binary) Formats() []string {
return []string{"binary", "bin"}
}