Skip to content

Commit

Permalink
fix: added HTMLTextTransformer
Browse files Browse the repository at this point in the history
  • Loading branch information
morlay committed Jul 7, 2020
1 parent 950518e commit 91eee1c
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions transformers/html_text_transformer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package transformers

import (
"context"
"io"
"io/ioutil"
"mime"
"net/textproto"
"reflect"

"github.com/go-courier/reflectx"
"github.com/go-courier/reflectx/typesutil"
)

func init() {
TransformerMgrDefault.Register(&HTMLTextTransformer{})
}

type HTMLTextTransformer struct {
}

func (t *HTMLTextTransformer) String() string {
return t.Names()[0]
}

func (HTMLTextTransformer) Names() []string {
return []string{"text/html", "html"}
}

func (HTMLTextTransformer) NamedByTag() string {
return ""
}

func (HTMLTextTransformer) New(context.Context, typesutil.Type) (Transformer, error) {
return &HTMLTextTransformer{}, nil
}

func (t *HTMLTextTransformer) EncodeToWriter(w io.Writer, v interface{}) (string, error) {
rv, ok := v.(reflect.Value)
if !ok {
rv = reflect.ValueOf(v)
}

return superWrite(w, func(w io.Writer) error {
if reflectx.IsBytes(rv.Type()) {
_, err := w.Write(rv.Bytes())
return err
}

data, err := reflectx.MarshalText(rv)
if err != nil {
return err
}
if _, err := w.Write(data); err != nil {
return err
}
return nil
}, mime.FormatMediaType(t.String(), map[string]string{
"charset": "utf-8",
}))
}

func (HTMLTextTransformer) DecodeFromReader(r io.Reader, v interface{}, headers ...textproto.MIMEHeader) error {
rv, ok := v.(reflect.Value)
if !ok {
rv = reflect.ValueOf(v)
}
data, err := ioutil.ReadAll(r)
if err != nil {
return err
}
if reflectx.IsBytes(rv.Type()) {
rv.SetBytes(data)
return nil
}
return reflectx.UnmarshalText(rv, data)
}

0 comments on commit 91eee1c

Please sign in to comment.