2022-07-03 00:56:37 +08:00
|
|
|
// Package request ...
|
|
|
|
//
|
|
|
|
// Description : request ...
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 2022-07-03 00:33
|
|
|
|
package request
|
|
|
|
|
|
|
|
import (
|
2022-07-14 11:08:03 +08:00
|
|
|
"bytes"
|
2022-07-03 00:56:37 +08:00
|
|
|
"errors"
|
2022-07-14 11:08:03 +08:00
|
|
|
"io/ioutil"
|
2022-07-03 00:56:37 +08:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
2022-10-16 16:45:47 +08:00
|
|
|
"github.com/go-playground/validator/v10"
|
|
|
|
|
2022-07-14 11:08:03 +08:00
|
|
|
"git.zhangdeman.cn/zhangdeman/gin/define"
|
|
|
|
|
2022-07-03 00:56:37 +08:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
|
|
|
|
|
|
|
// form 表单相关操作
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 00:51 2022/7/3
|
|
|
|
type form struct {
|
2022-10-16 16:45:47 +08:00
|
|
|
checkInstance *validator.Validate
|
2022-07-03 00:56:37 +08:00
|
|
|
}
|
|
|
|
|
2022-07-03 00:57:41 +08:00
|
|
|
// Parse 解析请求表单
|
2022-07-03 00:56:37 +08:00
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 00:34 2022/7/3
|
2022-07-03 00:57:41 +08:00
|
|
|
func (f *form) Parse(ctx *gin.Context, receiver interface{}) error {
|
2022-10-16 16:45:47 +08:00
|
|
|
|
2022-07-14 11:08:03 +08:00
|
|
|
requestBody, _ := ioutil.ReadAll(ctx.Request.Body)
|
|
|
|
// 请求信息写入上下文
|
|
|
|
ctx.Set(define.RecordRequestDataField, string(requestBody))
|
|
|
|
// 因为请求体被读一遍之后就没了,重新赋值 requestBody
|
|
|
|
ctx.Request.Body = ioutil.NopCloser(bytes.NewReader(requestBody))
|
2022-07-03 00:56:37 +08:00
|
|
|
method := strings.ToUpper(ctx.Request.Method)
|
|
|
|
if method == http.MethodGet ||
|
|
|
|
method == http.MethodPatch ||
|
|
|
|
method == http.MethodTrace ||
|
|
|
|
method == http.MethodConnect ||
|
|
|
|
method == http.MethodOptions {
|
2023-02-12 22:26:03 +08:00
|
|
|
return ctx.ShouldBindQuery(receiver)
|
2022-07-03 00:56:37 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if method == http.MethodPost ||
|
|
|
|
method == http.MethodPut ||
|
|
|
|
method == http.MethodDelete {
|
|
|
|
if ContentType.IsJson(ctx) {
|
2023-02-12 22:26:03 +08:00
|
|
|
return ctx.ShouldBindJSON(receiver)
|
2022-07-03 00:56:37 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if ContentType.IsFormURLEncoded(ctx) {
|
2023-02-12 22:26:03 +08:00
|
|
|
return ctx.ShouldBind(receiver)
|
2022-07-03 00:56:37 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return errors.New(ctx.ContentType() + " is not support")
|
|
|
|
}
|
|
|
|
return errors.New(method + " : request method is not support")
|
|
|
|
}
|