You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
92 lines
2.2 KiB
92 lines
2.2 KiB
package Middleware
|
|
|
|
import (
|
|
"bytes"
|
|
"dsBaseWeb/Model"
|
|
"dsBaseWeb/Utils/CommonUtil"
|
|
"encoding/json"
|
|
"github.com/gin-gonic/gin"
|
|
"strings"
|
|
)
|
|
|
|
//需要移除字段的map,key--->接口名称,value--->数组,描述有哪些列名
|
|
var removeFieldMap = make(map[string][]string, 0)
|
|
|
|
//初始化哪些接口需要进行字段的精减
|
|
func init() {
|
|
jsonBody := CommonUtil.ReadSwaggerJson()
|
|
m := jsonBody.(map[string]interface{})
|
|
n := m["paths"].(map[string]interface{})
|
|
for k, v := range n {
|
|
var removeList []interface{}
|
|
//遍历所有接口
|
|
t := v.(map[string]interface{})
|
|
httpType := "post"
|
|
//非空检查器
|
|
if t["get"] != nil {
|
|
httpType = "get"
|
|
}
|
|
//接口
|
|
r1 := t[httpType].(map[string]interface{})
|
|
if r1["x-removeswaggerfield"] != nil {
|
|
removeList = r1["x-removeswaggerfield"].([]interface{})
|
|
}
|
|
//移除指定的字段
|
|
var arr []string
|
|
for t := 0; t < len(removeList); t++ {
|
|
arr = append(arr, removeList[t].(string))
|
|
}
|
|
if len(arr) > 0 {
|
|
removeFieldMap[k] = arr
|
|
}
|
|
}
|
|
}
|
|
|
|
// bodyWriter是为了记录返回数据进行了重写
|
|
type bodyWriter struct {
|
|
gin.ResponseWriter
|
|
body *bytes.Buffer
|
|
ReqUri string
|
|
}
|
|
|
|
// 后置拦截器
|
|
// 用例地址:
|
|
// http://127.0.0.1:8002/base/area/PageGovArea
|
|
func (w bodyWriter) Write(b []byte) (int, error) {
|
|
//1、还原成json对象
|
|
var model Model.Res
|
|
json.Unmarshal(b, &model)
|
|
//2、去掉指定的列
|
|
var reqUri = w.ReqUri
|
|
if model.List != nil {
|
|
list := model.List.([]interface{})
|
|
for i := 0; i < len(list); i++ {
|
|
_m := list[i].(map[string]interface{})
|
|
//去掉接口名称map中所有需要干掉的列
|
|
for j := 0; j < len(removeFieldMap[reqUri]); j++ {
|
|
delete(_m, removeFieldMap[reqUri][j])
|
|
}
|
|
}
|
|
//序列化后重新输出
|
|
b, _ = json.Marshal(model)
|
|
}
|
|
w.body.Write(b)
|
|
return w.ResponseWriter.Write(b)
|
|
}
|
|
|
|
//后置拦截器
|
|
func AfterHandler() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
//这里用来后置拦截
|
|
reqUri := strings.Split(c.Request.RequestURI, "?")[0]
|
|
//如果需要进行处理
|
|
_, exist := removeFieldMap[reqUri]
|
|
if exist {
|
|
//复制返回器,准备去除多余的列
|
|
c.Writer = &bodyWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer, ReqUri: reqUri}
|
|
}
|
|
// 处理请求
|
|
c.Next()
|
|
}
|
|
}
|