github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/httptransport/transformer/tsfm_html.go (about) 1 package transformer 2 3 import ( 4 "context" 5 "io" 6 "net/textproto" 7 "reflect" 8 9 "github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/httpx" 10 "github.com/machinefi/w3bstream/pkg/depends/x/textx" 11 "github.com/machinefi/w3bstream/pkg/depends/x/typesx" 12 ) 13 14 const HTMLTsfName = "text/html" 15 16 func init() { DefaultFactory.Register(&HTMLText{}) } 17 18 type HTMLText struct{} 19 20 func (t *HTMLText) String() string { return HTMLTsfName } 21 22 func (HTMLText) Names() []string { return []string{HTMLTsfName, "html"} } 23 24 func (HTMLText) NamedByTag() string { return "" } 25 26 func (HTMLText) New(context.Context, typesx.Type) (Transformer, error) { return &HTMLText{}, nil } 27 28 func (t *HTMLText) EncodeTo(ctx context.Context, w io.Writer, v interface{}) error { 29 rv, ok := v.(reflect.Value) 30 if !ok { 31 rv = reflect.ValueOf(v) 32 } 33 34 httpx.MaybeWriteHeader(ctx, w, t.String(), map[string]string{ 35 "charset": "utf-8", 36 }) 37 38 data, err := textx.MarshalText(rv, true) 39 if err != nil { 40 return err 41 } 42 43 _, err = w.Write(data) 44 return err 45 } 46 47 func (HTMLText) DecodeFrom(_ context.Context, r io.Reader, v interface{}, _ ...textproto.MIMEHeader) error { 48 rv, ok := v.(reflect.Value) 49 if !ok { 50 rv = reflect.ValueOf(v) 51 } 52 data, err := io.ReadAll(r) 53 if err != nil { 54 return err 55 } 56 return textx.UnmarshalText(rv, data, true) 57 }