增加form url encode解析

This commit is contained in:
白茶清欢 2024-10-22 17:20:30 +08:00
parent 56441151cf
commit cffb0c8779
2 changed files with 37 additions and 0 deletions

View File

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

View File

@ -6,3 +6,39 @@
//
// Date : 2024-10-22 16:43
package parse_body
import (
"encoding/json"
"git.zhangdeman.cn/zhangdeman/consts"
"git.zhangdeman.cn/zhangdeman/serialize"
"github.com/gin-gonic/gin"
)
type FormUrlEncode struct {
base
}
func (f FormUrlEncode) Parse(ctx *gin.Context, receiver any) ([]byte, error) {
if err := ctx.Request.ParseForm(); nil != err {
return nil, err
}
body := map[string]string{}
for paramName, itemParam := range ctx.Request.PostForm {
if len(itemParam) > 0 {
body[paramName] = itemParam[0]
} else {
body[paramName] = ""
}
}
byteData, _ := json.Marshal(body)
if nil != receiver {
if err := serialize.JSON.UnmarshalWithNumber(byteData, receiver); nil != receiver {
return nil, err
}
}
return byteData, nil
}
func (f FormUrlEncode) ContentType() string {
return consts.MimeTypeXWWWFormUrlencoded
}