/
text_html.go
70 lines (57 loc) · 1.31 KB
/
text_html.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package html
import (
"context"
"io"
"net/textproto"
"reflect"
"github.com/octohelm/courier/pkg/transformer/core"
transformer "github.com/octohelm/courier/pkg/transformer/core"
encodingx "github.com/octohelm/x/encoding"
typesutil "github.com/octohelm/x/types"
)
func init() {
transformer.Register(&textHtml{})
}
type textHtml struct {
}
func (*textHtml) NamedByTag() string {
return ""
}
func (t *textHtml) String() string {
return t.Names()[0]
}
func (*textHtml) Names() []string {
return []string{"text/html", "html"}
}
func (*textHtml) New(context.Context, typesutil.Type) (transformer.Transformer, error) {
return &textHtml{}, nil
}
func (t *textHtml) EncodeTo(ctx context.Context, w io.Writer, v any) error {
rv, ok := v.(reflect.Value)
if !ok {
rv = reflect.ValueOf(v)
}
core.WriteHeader(ctx, w, t.String(), map[string]string{
"charset": "utf-8",
})
data, err := encodingx.MarshalText(rv)
if err != nil {
return err
}
if _, err := w.Write(data); err != nil {
return err
}
return nil
}
func (*textHtml) DecodeFrom(ctx context.Context, r io.ReadCloser, v any, headers ...textproto.MIMEHeader) error {
defer r.Close()
rv, ok := v.(reflect.Value)
if !ok {
rv = reflect.ValueOf(v)
}
data, err := io.ReadAll(r)
if err != nil {
return err
}
return encodingx.UnmarshalText(rv, data)
}