增加json的请求Body解析

This commit is contained in:
白茶清欢 2024-10-22 17:14:53 +08:00
parent 2c99eb9656
commit 56441151cf
4 changed files with 120 additions and 0 deletions

12
init.go Normal file
View File

@ -0,0 +1,12 @@
// Package gin ...
//
// Description : gin ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-10-22 17:01
package gin
import (
_ "git.zhangdeman.cn/zhangdeman/gin/request/parse_body"
)

View File

@ -0,0 +1,46 @@
// Package parse_body ...
//
// Description : parse_body ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-10-22 16:51
package parse_body
import (
"bytes"
"github.com/gin-gonic/gin"
"io"
)
type base struct {
}
// Unmarshal 反序列化方法,可以不指定
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:54 2024/10/22
func (b base) Unmarshal() func(sourceData []byte, receiver any) error {
return nil
}
// DoParse 解析
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 17:08 2024/10/22
func (b base) DoParse(ctx *gin.Context, receiver any, unmarshalFunc func(sourceData []byte, receiver any) error) ([]byte, error) {
data, err := io.ReadAll(ctx.Request.Body)
if nil != err {
return nil, err
}
ctx.Request.Body = io.NopCloser(bytes.NewBuffer(data))
if nil == unmarshalFunc || nil == receiver {
return data, nil
}
if err := unmarshalFunc(data, receiver); nil != err {
return nil, err
}
return data, err
}

View File

@ -18,6 +18,15 @@ var (
requestBodyParseAdaptorTable = map[string]abstract.RequestBodyParseAdaptor{}
)
func init() {
adaptorList := []abstract.RequestBodyParseAdaptor{
JsonAdaptor{},
}
for _, itemAdaptor := range adaptorList {
Register(itemAdaptor)
}
}
// Register 注册适配器实例
//
// Author : go_developer@163.com<白茶清欢>
@ -45,3 +54,15 @@ func Execute(ctx *gin.Context, receiver any) ([]byte, error) {
return parseResult, err
}
}
// 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
}

View File

@ -6,3 +6,44 @@
//
// Date : 2024-10-22 16:42
package parse_body
import (
"git.zhangdeman.cn/zhangdeman/consts"
"git.zhangdeman.cn/zhangdeman/serialize"
"github.com/gin-gonic/gin"
)
type JsonAdaptor struct {
base
}
// Parse 解析json请求体
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 17:13 2024/10/22
func (j JsonAdaptor) Parse(ctx *gin.Context, receiver any) ([]byte, error) {
unmarshalFunc := j.Unmarshal()
if nil == unmarshalFunc {
unmarshalFunc = serialize.JSON.UnmarshalWithNumber
}
return j.DoParse(ctx, receiver, unmarshalFunc)
}
// Unmarshal 指定解析方法
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:56 2024/10/22
func (j JsonAdaptor) Unmarshal() func(sourceData []byte, receiver any) error {
return serialize.JSON.UnmarshalWithNumber
}
// ContentType 请求类型固定返回json
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:59 2024/10/22
func (j JsonAdaptor) ContentType() string {
return consts.MimeTypeJson
}