12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- // Copyright 2019 getensh.com. All rights reserved.
- // Use of this source code is governed by getensh.com.
- package util
- import (
- "bytes"
- "fmt"
- "io/ioutil"
- "github.com/gin-gonic/gin"
- jsoniter "github.com/json-iterator/go"
- )
- // 替换encoding/json包
- var json = jsoniter.ConfigCompatibleWithStandardLibrary
- // ShouldBind 统一进行http参数解析, header, path, query, body 可为nil
- func ShouldBind(ctx *gin.Context, header, path, query, body interface{}) error {
- // 解析header参数
- if header != nil {
- if err := ctx.ShouldBindHeader(header); err != nil {
- s, _ := json.MarshalToString(ctx.Request.Header)
- return fmt.Errorf("ctx.ShouldBindHeader, err: %+v, params: %s", err, s)
- }
- }
- // 解析path参数
- if path != nil {
- if err := ctx.ShouldBindUri(path); err != nil {
- s, _ := json.MarshalToString(ctx.FullPath)
- return fmt.Errorf("ctx.ShouldBindUri, err: %+v, params: %s", err, s)
- }
- }
- // 解析query参数
- if query != nil {
- if err := ctx.ShouldBindQuery(query); err != nil {
- s, _ := json.MarshalToString(ctx.Request.URL.RawQuery)
- return fmt.Errorf("ctx.ShouldBindQuery, err: %+v, params: %s", err, s)
- }
- }
- // 解析body参数
- if body != nil {
- // 读出body数据
- buf, err := ctx.GetRawData()
- if err == nil {
- ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buf)) // 关键: 回写body,便于后面使用
- }
- // 解析body参数,本方法会把body取完
- if err := ctx.ShouldBind(body); err != nil {
- return fmt.Errorf("ctx.ShouldBind, err: %+v, params: %s", err, string(buf))
- }
- }
- return nil
- }
|