Compare commits
2 Commits
Author | SHA1 | Date | |
---|---|---|---|
0f33dbcfaf | |||
43b5b349e6 |
75
xml.go
75
xml.go
@@ -2,7 +2,9 @@
|
||||
package xml // import "go.unistack.org/micro-codec-xml/v3"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
|
||||
pb "go.unistack.org/micro-proto/v3/codec"
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
@@ -19,6 +21,18 @@ const (
|
||||
flattenTag = "flatten"
|
||||
)
|
||||
|
||||
type unmarshalStrictKey struct{}
|
||||
|
||||
func UnmarshalStrict(b bool) codec.Option {
|
||||
return codec.SetOption(unmarshalStrictKey{}, b)
|
||||
}
|
||||
|
||||
type unmarshalXML11Key struct{}
|
||||
|
||||
func UnmarshalXML11(b bool) codec.Option {
|
||||
return codec.SetOption(unmarshalXML11Key{}, b)
|
||||
}
|
||||
|
||||
func (c *xmlCodec) Marshal(v interface{}, opts ...codec.Option) ([]byte, error) {
|
||||
if v == nil {
|
||||
return nil, nil
|
||||
@@ -80,7 +94,66 @@ func (c *xmlCodec) Unmarshal(b []byte, v interface{}, opts ...codec.Option) erro
|
||||
return nil
|
||||
}
|
||||
|
||||
return xml.Unmarshal(b, v)
|
||||
var unmarshalStrict bool
|
||||
var unmarshalXML11 bool
|
||||
if options.Context != nil {
|
||||
if v, ok := options.Context.Value(unmarshalStrictKey{}).(bool); ok {
|
||||
unmarshalStrict = v
|
||||
}
|
||||
if v, ok := options.Context.Value(unmarshalXML11Key{}).(bool); ok {
|
||||
unmarshalXML11 = v
|
||||
}
|
||||
}
|
||||
|
||||
var r io.Reader
|
||||
|
||||
if unmarshalXML11 {
|
||||
r = newReader(b)
|
||||
} else {
|
||||
r = bytes.NewReader(b)
|
||||
}
|
||||
|
||||
d := xml.NewDecoder(r)
|
||||
|
||||
if unmarshalStrict {
|
||||
d.Strict = true
|
||||
}
|
||||
|
||||
return d.Decode(v)
|
||||
}
|
||||
|
||||
type reader struct {
|
||||
s []byte
|
||||
i int64 // current reading index
|
||||
prevRune int // index of previous rune; or < 0
|
||||
skip bool
|
||||
}
|
||||
|
||||
func newReader(b []byte) io.Reader {
|
||||
return &reader{b, 0, -1, false}
|
||||
}
|
||||
|
||||
var (
|
||||
srcP = []byte(`version="1.1"`)
|
||||
srcL = len(srcP)
|
||||
dstP = []byte(`version="1.0"`)
|
||||
)
|
||||
|
||||
func (r *reader) Read(b []byte) (n int, err error) {
|
||||
if r.i >= int64(len(r.s)) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
r.prevRune = -1
|
||||
n = copy(b, r.s[r.i:])
|
||||
if !r.skip {
|
||||
if idx := bytes.Index(b, srcP); idx > 0 {
|
||||
copy(b[idx:idx+srcL], dstP)
|
||||
r.skip = true
|
||||
}
|
||||
}
|
||||
|
||||
r.i += int64(n)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *xmlCodec) String() string {
|
||||
|
Reference in New Issue
Block a user