github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/httptransport/transformer/tsfm_xml.go (about) 1 package transformer 2 3 import ( 4 "context" 5 "encoding/xml" 6 "io" 7 "net/textproto" 8 "reflect" 9 10 "github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/httpx" 11 "github.com/machinefi/w3bstream/pkg/depends/x/typesx" 12 ) 13 14 func init() { DefaultFactory.Register(&XML{}) } 15 16 type XML struct{} 17 18 func (XML) Names() []string { return []string{httpx.MIME_XML, "xml"} } 19 20 func (t *XML) String() string { return httpx.MIME_XML } 21 22 func (XML) NamedByTag() string { return "xml" } 23 24 func (XML) New(context.Context, typesx.Type) (Transformer, error) { 25 return &XML{}, nil 26 } 27 28 func (t *XML) EncodeTo(ctx context.Context, w io.Writer, v interface{}) error { 29 if rv, ok := v.(reflect.Value); ok { 30 v = rv.Interface() 31 } 32 33 httpx.MaybeWriteHeader(ctx, w, t.String(), map[string]string{ 34 "charset": "utf-8", 35 }) 36 37 return xml.NewEncoder(w).Encode(v) 38 } 39 40 func (XML) DecodeFrom(_ context.Context, r io.Reader, v interface{}, _ ...textproto.MIMEHeader) error { 41 if rv, ok := v.(reflect.Value); ok { 42 if rv.Kind() != reflect.Ptr && rv.CanAddr() { 43 rv = rv.Addr() 44 } 45 v = rv.Interface() 46 } 47 d := xml.NewDecoder(r) 48 err := d.Decode(v) 49 if err != nil { 50 // TODO resolve field path by InputOffset() 51 return err 52 } 53 return nil 54 }