2024-10-22 16:49:45 +08:00
|
|
|
|
// Package parse_body ...
|
|
|
|
|
//
|
|
|
|
|
// Description : parse_body ...
|
|
|
|
|
//
|
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
|
//
|
|
|
|
|
// Date : 2024-10-22 16:43
|
|
|
|
|
package parse_body
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"errors"
|
|
|
|
|
"git.zhangdeman.cn/zhangdeman/gin/request/abstract"
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
"strings"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var (
|
|
|
|
|
requestBodyParseAdaptorTable = map[string]abstract.RequestBodyParseAdaptor{}
|
|
|
|
|
)
|
|
|
|
|
|
2024-10-22 17:14:53 +08:00
|
|
|
|
func init() {
|
|
|
|
|
adaptorList := []abstract.RequestBodyParseAdaptor{
|
|
|
|
|
JsonAdaptor{},
|
2024-10-22 17:20:30 +08:00
|
|
|
|
FormUrlEncode{},
|
2024-11-04 17:06:51 +08:00
|
|
|
|
XmlAdaptor{},
|
2024-10-22 17:14:53 +08:00
|
|
|
|
}
|
|
|
|
|
for _, itemAdaptor := range adaptorList {
|
|
|
|
|
Register(itemAdaptor)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-22 16:49:45 +08:00
|
|
|
|
// Register 注册适配器实例
|
|
|
|
|
//
|
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
|
//
|
|
|
|
|
// Date : 16:45 2024/10/22
|
|
|
|
|
func Register(adaptor abstract.RequestBodyParseAdaptor) {
|
|
|
|
|
if nil == adaptor {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
requestBodyParseAdaptorTable[adaptor.ContentType()] = adaptor
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Execute 解析请求BODY数据
|
|
|
|
|
func Execute(ctx *gin.Context, receiver any) ([]byte, error) {
|
|
|
|
|
contentType := strings.ToLower(strings.ReplaceAll(ctx.ContentType(), " ", ""))
|
|
|
|
|
// 裁剪出真实的类型,之所以截取,是因为 content_type 中可能还包含编码信息, 如 : application/json;charset=utf8
|
|
|
|
|
contentTypeArr := strings.Split(contentType, ";")
|
|
|
|
|
contentType = contentTypeArr[0]
|
|
|
|
|
if _, exist := requestBodyParseAdaptorTable[contentType]; !exist {
|
|
|
|
|
return nil, errors.New(contentType + " : adaptor not found")
|
|
|
|
|
}
|
|
|
|
|
if parseResult, err := requestBodyParseAdaptorTable[contentType].Parse(ctx, receiver); nil != err {
|
|
|
|
|
return nil, err
|
|
|
|
|
} else {
|
|
|
|
|
return parseResult, err
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-10-22 17:14:53 +08:00
|
|
|
|
|
|
|
|
|
// ExecuteForMap 高层级包装,表单解析为map
|
|
|
|
|
func ExecuteForMap(ctx *gin.Context) (map[string]any, error) {
|
|
|
|
|
var (
|
|
|
|
|
err error
|
|
|
|
|
result map[string]any
|
|
|
|
|
)
|
|
|
|
|
if _, err = Execute(ctx, &result); nil != err {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return result, nil
|
|
|
|
|
}
|