升级请求体解析 #1

Merged
zhangdeman merged 8 commits from feature/parse_body into master 2024-11-05 17:32:44 +08:00
2 changed files with 37 additions and 0 deletions
Showing only changes of commit cffb0c8779 - Show all commits

View File

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

View File

@ -6,3 +6,39 @@
// //
// Date : 2024-10-22 16:43 // Date : 2024-10-22 16:43
package parse_body 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
}