json_filter/filter.go

145 lines
3.2 KiB
Go

// Package filter ...
//
// Description : filter ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2022-07-04 17:47
package filter
import (
"fmt"
"strings"
"git.zhangdeman.cn/zhangdeman/util"
"github.com/Jeffail/gabs"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
)
// MapRule 映射规则
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:21 2022/7/4
type MapRule struct {
SourcePath string `json:"source_path"` // 原路径
MapPath string `json:"map_path"` // 映射路径
Required bool `json:"required"` // 必须存在
DataType string `json:"data_type"` // 数据类型
DefaultValue string `json:"default_value"` // 默认值, 以字符串传入, 会转换成 DataType
}
// NewFilter 过滤器实例
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:54 2022/7/4
func NewFilter(sourceData string, filterRuleList []MapRule) *filter {
return &filter{
sourceData: sourceData,
filterRuleList: filterRuleList,
jsonObj: &gabs.Container{},
}
}
// filter 数据过滤
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:58 2022/7/4
type filter struct {
sourceData string
filterRuleList []MapRule
jsonObj *gabs.Container // 生成的json对象实例
}
// Deal ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:59 2022/7/4
func (f *filter) Deal() ([]byte, error) {
for _, rule := range f.filterRuleList {
if strings.Contains(rule.SourcePath, "[]") {
// 对于list的处理
continue
}
sourceResult := gjson.Get(f.sourceData, rule.SourcePath)
sourceVal := sourceResult.String()
if !sourceResult.Exists() {
// 不存在, 使用默认值
sourceVal = rule.DefaultValue
}
formatVal, err := f.getValue(rule.DataType, sourceVal)
if nil != err {
return nil, fmt.Errorf("%s = %v can not convert to %s : %s", rule.SourcePath, sourceResult.Value(), rule.DataType, err.Error())
}
if _, err := f.jsonObj.SetP(formatVal, rule.MapPath); nil != err {
return nil, fmt.Errorf("%s set val = %v fail : %s", rule.MapPath, formatVal, err.Error())
}
}
return f.jsonObj.EncodeJSON(), nil
}
// getValue 获取值
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:25 2022/7/4
func (f *filter) getValue(dataType string, defaultValue string) (interface{}, error) {
switch dataType {
case "int8":
fallthrough
case "int16":
fallthrough
case "int32":
fallthrough
case "int64":
fallthrough
case "int":
var (
err error
val int64
)
err = util.ConvertAssign(&val, defaultValue)
return val, err
case "uint8":
fallthrough
case "uint16":
fallthrough
case "uint32":
fallthrough
case "uint64":
fallthrough
case "uint":
var (
err error
val uint64
)
err = util.ConvertAssign(&val, defaultValue)
return val, err
case "bool":
var (
err error
val bool
)
err = util.ConvertAssign(&val, defaultValue)
return val, err
case "float32":
fallthrough
case "float64":
var (
err error
val float64
)
err = util.ConvertAssign(&val, defaultValue)
return val, err
case "string":
return defaultValue, nil
default:
return nil, errors.New(dataType + " is not support!")
}
}