github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/httptransport/transformer/tsfm_plain_text.go (about)

     1  package transformer
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"net/textproto"
     7  
     8  	"github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/httpx"
     9  	"github.com/machinefi/w3bstream/pkg/depends/x/textx"
    10  	"github.com/machinefi/w3bstream/pkg/depends/x/typesx"
    11  )
    12  
    13  func init() { DefaultFactory.Register(&PlainText{}) }
    14  
    15  type PlainText struct{}
    16  
    17  func (t *PlainText) String() string { return httpx.MIME_PLAIN_TEXT }
    18  
    19  func (PlainText) Names() []string {
    20  	return []string{httpx.MIME_PLAIN_TEXT, "plain", "text", "txt"}
    21  }
    22  
    23  func (PlainText) New(context.Context, typesx.Type) (Transformer, error) { return &PlainText{}, nil }
    24  
    25  func (t *PlainText) EncodeTo(ctx context.Context, w io.Writer, v interface{}) error {
    26  	httpx.MaybeWriteHeader(ctx, w, t.String(), map[string]string{
    27  		"charset": "utf-8",
    28  	})
    29  
    30  	data, err := textx.MarshalText(v, true)
    31  	if err != nil {
    32  		return err
    33  	}
    34  
    35  	if _, err := w.Write(data); err != nil {
    36  		return err
    37  	}
    38  
    39  	return nil
    40  }
    41  
    42  func (t *PlainText) DecodeFrom(_ context.Context, r io.Reader, v interface{}, _ ...textproto.MIMEHeader) error {
    43  	switch x := r.(type) {
    44  	case CanString:
    45  		raw := x.String()
    46  		if x, ok := v.(*string); ok {
    47  			*x = raw
    48  			return nil
    49  		}
    50  		return textx.UnmarshalText(v, []byte(raw), true)
    51  	case CanInterface:
    52  		if raw, ok := x.Interface().(string); ok {
    53  			if x, ok := v.(*string); ok {
    54  				*x = raw
    55  				return nil
    56  			}
    57  			return textx.UnmarshalText(v, []byte(raw), true)
    58  		}
    59  	}
    60  	data, err := io.ReadAll(r)
    61  	if err != nil {
    62  		return err
    63  	}
    64  	return textx.UnmarshalText(v, data, true)
    65  }