-
Notifications
You must be signed in to change notification settings - Fork 34
/
tsfm_plain_text.go
65 lines (53 loc) · 1.47 KB
/
tsfm_plain_text.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
package transformer
import (
"context"
"io"
"net/textproto"
"github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/httpx"
"github.com/machinefi/w3bstream/pkg/depends/x/textx"
"github.com/machinefi/w3bstream/pkg/depends/x/typesx"
)
func init() { DefaultFactory.Register(&PlainText{}) }
type PlainText struct{}
func (t *PlainText) String() string { return httpx.MIME_PLAIN_TEXT }
func (PlainText) Names() []string {
return []string{httpx.MIME_PLAIN_TEXT, "plain", "text", "txt"}
}
func (PlainText) New(context.Context, typesx.Type) (Transformer, error) { return &PlainText{}, nil }
func (t *PlainText) EncodeTo(ctx context.Context, w io.Writer, v interface{}) error {
httpx.MaybeWriteHeader(ctx, w, t.String(), map[string]string{
"charset": "utf-8",
})
data, err := textx.MarshalText(v, true)
if err != nil {
return err
}
if _, err := w.Write(data); err != nil {
return err
}
return nil
}
func (t *PlainText) DecodeFrom(_ context.Context, r io.Reader, v interface{}, _ ...textproto.MIMEHeader) error {
switch x := r.(type) {
case CanString:
raw := x.String()
if x, ok := v.(*string); ok {
*x = raw
return nil
}
return textx.UnmarshalText(v, []byte(raw), true)
case CanInterface:
if raw, ok := x.Interface().(string); ok {
if x, ok := v.(*string); ok {
*x = raw
return nil
}
return textx.UnmarshalText(v, []byte(raw), true)
}
}
data, err := io.ReadAll(r)
if err != nil {
return err
}
return textx.UnmarshalText(v, data, true)
}