123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- // 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"
- )
- // 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
- }
|