yjp b62529b5eb 修改项目结构 2 months ago
..
README.md b62529b5eb 修改项目结构 2 months ago
log.go b62529b5eb 修改项目结构 2 months ago
schema.yaml b62529b5eb 修改项目结构 2 months ago
schema_doc.go b62529b5eb 修改项目结构 2 months ago
schema_node.go b62529b5eb 修改项目结构 2 months ago
test.yaml b62529b5eb 修改项目结构 2 months ago
utils.go b62529b5eb 修改项目结构 2 months ago
yaml_checker_test.go b62529b5eb 修改项目结构 2 months ago

README.md

yaml_checker

一、校验原理说明

涉及两种类型的YAML文件:schema文件和被校验文件,校验器的原理就是通过schema定义YAML文件的结构,利用schema定义检查被校验文件的有效性。

schema文件必须是schema为根节点的YAML文件,schema节点类型有object和field两种,如果需要将定义的object或者field类型节点升级为数组,只需要as_array字段为true即可。

object类型的节点属性:

type: object # 必须为object
name: # 必传,yaml对象的名称
describe: # 必传,yaml对象的描述
required: # 非必传,该字段在被检测文件中是否是必传字段,默认为false
as_array: # 非必传,是否升级为数组类型,默认为false
fields: # 子字段定义,可以是object或者field类型的节点定义

field类型的节点属性:

type: field # 必须为field
name: # 必传,yaml对象的名称
describe: # 必传,yaml对象的描述
required: # 非必传,该字段在被检测文件中是否是必传字段,默认为false
as_array: # 非必传,是否升级为数组类型,默认为false
field_type: # 字段类型,可以是string,int,bool

给出一个较完整的示例:

schema:
  - type: field
    name: test_field_array
    describe: 测试field数组(必传)
    required: true
    as_array: true
    field_type: string
  - type: field
    name: test_field
    describe: 测试field(必传)
    required: true
    field_type: string
  - type: object
    name: test_obj_array
    describe: 测试对象(必传)
    required: true
    as_array: true
    fields:
      - type: field
        name: field
        describe: 测试对象字段类型字段(非必传)
        required: false
        field_type: string
  - type: object
    name: test_obj
    describe: 测试对象(必传)
    required: true
    fields:
      - type: field
        name: field_array
        describe: 测试对象字段类型数组字段(必传)
        required: true
        as_array: true
        field_type: string
      - type: field
        name: field
        describe: 测试对象字段类型字段(非必传)
        required: false
        field_type: string
      - type: object
        name: obj_array
        describe: 测试对象包含对象数组(必传)
        required: true
        as_array: true
        fields:
          - type: field
            name: obj_array_field1
            describe: 对象数组字段1(必传)
            required: true
            field_type: string
          - type: field
            name: obj_array_field2
            describe: 对象数组字段2(非必传)
            required: false
            field_type: string

一个有效的YAML文件,如下所示:

test_field_array:
  - aaa
  - bbb
  - ccc
test_field: ddd
test_obj_array:
  - field: aaa
test_obj:
  field_array:
    - aaa
    - bbb
  field: ccc
  obj_array:
    - obj_array_field1: aaa
    - obj_array_field1: bbb
      obj_array_field2: ccc

二、包使用说明

首先导入包

import "git.sxidc.com/go-tools/yaml_checker"
schemaDoc, err := NewSchemaDoc("schema.yaml")
if err != nil {
    t.Fatal(err)
}

err = schemaDoc.ValidateFile("test.yaml")
if err != nil {
    t.Fatal(err)
}

/*
err = schemaDoc.ValidateMap(yamlMap)
if err != nil {
    t.Fatal(err)
}
*/