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.

108 lines
3.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package CheckHandler
import (
"github.com/gin-gonic/gin"
"strconv"
"strings"
)
//在注释标签中声明的标识字符串X-FloatLimit
var floatLimit = "x-floatlimit"
//形成一个map,用于O(1)速度获取到一个接口是不是需要进行判断拦截注意一个接口可以存在post+get两种形式所以map里面是一个数组需要遍历
type floatLimitStruct struct {
parameterName string
httpType string
must bool
}
//长度限制的map,以string为key(key的命名是接口名+"_get" 或者 接口名+"_post"),里面是floatLimitStruct形式的数组
var floatLimitMap = make(map[string][]floatLimitStruct)
/**
功能:功能函数,添当前的检查字典里
*/
func floatAddToMap(d map[string]interface{},t map[string]interface{},k string,httpType string){
var floatLimitArray []floatLimitStruct
d = t[httpType].(map[string]interface{})
if d != nil && d[floatLimit] != nil {
for _, value := range d[floatLimit].([]interface{}) {
var t floatLimitStruct
t.parameterName = value.(string)
t.httpType = httpType
//此参数是否为必填写项
for _, v2 := range d["parameters"].([]interface{}) {
c2 := v2.(map[string]interface{})
for k2, v2 := range c2 {
if k2 == "required" {
t.must = v2.(bool) //标识是否是必须项
}
}
}
floatLimitArray = append(floatLimitArray, t)
}
floatLimitMap[k+"_"+httpType] = floatLimitArray
}
}
/**
功能:初始化浮点数限制字典
*/
func floatLimitInit(inter interface{}) map[string][]floatLimitStruct {
//参数检查器
m := inter.(map[string]interface{})
n := m["paths"].(map[string]interface{})
for k, v := range n {
t := v.(map[string]interface{})
//参数长度检查器
var d map[string]interface{}
if t["get"] != nil {
floatAddToMap(d,t,k,"get")
}
if t["post"] != nil {
floatAddToMap(d,t,k,"post")
}
}
return floatLimitMap
}
/**
功能:检查字符串是否为浮点数
作者:黄海
时间2020-03-17
*/
func floatLimitIsLegal(c *gin.Context, interName string) (bool, ResultStruct) {
var resultStruct ResultStruct
//接口传入的请求方式:get?post?
codeHttpType := strings.ToLower(c.Request.Method)
//1、如果此接口地址需要进行参数长度检查
if floatLimitMap[interName+"_"+codeHttpType] != nil {
arr := floatLimitMap[interName+"_"+codeHttpType]
resultStruct.InterfaceName = interName
//遍历arr
for i := 0; i < len(arr); i++ {
parameterName := arr[i].parameterName
httpType := arr[i].httpType
var p string
if httpType == "get" {
p = c.Query(parameterName)
} else {
p = c.PostForm(parameterName)
}
resultStruct.Parameter = parameterName
//为空,不需要检查,通过
if p == "" && !arr[i].must {
return true, resultStruct
}
//为空,需要检查,禁止
if p == "" && arr[i].must{
resultStruct.Message = "参数没有找到!"
return false, resultStruct
}
if _, err := strconv.ParseFloat(p, 64); err != nil {
resultStruct.HttpType = httpType
resultStruct.Message = "不是浮点数!"
return false, resultStruct
}
}
}
return true, resultStruct
}