支持xml body解析

This commit is contained in:
2024-11-04 17:06:51 +08:00
parent f6db9e8edb
commit 6a917d338a
4 changed files with 43 additions and 1 deletions

View File

@ -22,6 +22,7 @@ func init() {
adaptorList := []abstract.RequestBodyParseAdaptor{
JsonAdaptor{},
FormUrlEncode{},
XmlAdaptor{},
}
for _, itemAdaptor := range adaptorList {
Register(itemAdaptor)

View File

@ -6,3 +6,37 @@
//
// Date : 2024-10-22 16:42
package parse_body
import (
"bytes"
"git.zhangdeman.cn/zhangdeman/consts"
"git.zhangdeman.cn/zhangdeman/serialize"
"github.com/gin-gonic/gin"
"github.com/sbabiv/xml2map"
)
type XmlAdaptor struct {
base
}
func (x XmlAdaptor) Parse(ctx *gin.Context, receiver any) ([]byte, error) {
unmarshalFunc := x.Unmarshal()
if nil == unmarshalFunc {
unmarshalFunc = serialize.Xml.UnmarshalWithNumber
}
return x.DoParse(ctx, receiver, unmarshalFunc)
}
func (x XmlAdaptor) Unmarshal() func(sourceData []byte, receiver any) error {
return func(sourceData []byte, receiver any) error {
res, err := xml2map.NewDecoder(bytes.NewReader(sourceData)).Decode()
if nil != err {
return err
}
return serialize.JSON.Transition(res, receiver)
}
}
func (x XmlAdaptor) ContentType() string {
return consts.MimeTypeXml
}