package yaml_checker import ( "github.com/pkg/errors" "reflect" ) type SchemaNode interface { Validate(yamlMap map[string]any) error } type BaseNamingSchemaNode struct { Type string Name string Describe string Required bool } type ObjectSchemaNode struct { BaseNamingSchemaNode AsArray bool Fields []SchemaNode } func (schema *ObjectSchemaNode) Validate(yamlMap map[string]any) error { yamlValue, ok := yamlMap[schema.Name] if !ok { if schema.Required { return errors.New(schemaNodeTypeObject + "类型的yaml节点必须有" + schema.Name) } return nil } if yamlValue == nil { return errors.New(schemaNodeTypeObject + "类型的yaml节点的" + schema.Name + "字段没有赋值") } if schema.AsArray { sliceParamValues, ok := yamlValue.([]any) if !ok { return errors.New(schemaNodeTypeObject + "类型节点" + schema.Name + "的as_array为true,但是值不是数组") } for _, sliceParamValue := range sliceParamValues { sliceParamMapValue, ok := sliceParamValue.(map[string]any) if !ok { return errors.New(schemaNodeTypeObject + "类型节点" + schema.Name + "的值类型转换失败") } err := schema.validateValue(sliceParamMapValue) if err != nil { return err } } return nil } yamlMapValue, ok := yamlValue.(map[string]any) if !ok { return errors.New(schemaNodeTypeObject + "类型节点不是键值对") } err := schema.validateValue(yamlMapValue) if err != nil { return err } return nil } func (schema *ObjectSchemaNode) validateValue(yamlMap map[string]any) error { for _, field := range schema.Fields { err := field.Validate(yamlMap) if err != nil { return err } } return nil } type FieldSchemaNode struct { BaseNamingSchemaNode AsArray bool FieldType string } func (schema *FieldSchemaNode) Validate(yamlMap map[string]any) error { yamlValue, ok := yamlMap[schema.Name] if !ok { if schema.Required { return errors.New(schemaNodeTypeField + "类型的yaml节点必须有" + schema.Name) } return nil } if yamlValue == nil { return errors.New(schemaNodeTypeField + "类型的yaml节点的" + schema.Name + "字段没有赋值") } if schema.AsArray { sliceParamValues, ok := yamlValue.([]any) if !ok { return errors.New(schemaNodeTypeField + "类型节点as_array为true,但是值不是数组") } for _, sliceParamValue := range sliceParamValues { err := schema.validateValue(sliceParamValue) if err != nil { return err } } return nil } err := schema.validateValue(yamlValue) if err != nil { return err } return nil } func (schema *FieldSchemaNode) validateValue(paramValue any) error { valueType := reflect.TypeOf(paramValue).String() if valueType != schema.FieldType { return errors.New(schemaNodeTypeField + "类型节点的" + schema.Name + "字段期望类型为: " + schema.FieldType + " 实际类型为: " + valueType) } return nil }