devtron 依赖解析:invopop/jsonschema 如何用 Go 反射生成 JSON Schema(Draft 2020-12)
devtron 依赖解析:invopop/jsonschema 如何用 Go 反射生成 JSON Schema(Draft 2020-12)
导读
invopop/jsonschema 是一个通过 Go 反射机制自动生成 JSON Schema](http://json-schema.org/latest/json-schema-validation.html) 的第三方库,在本仓库中作为 v0.7.0 依赖被引入(见 [go.mod),并被 devtron 的 SchemaUtils.go 封装为泛型工具 GetSchemaFromType,用于为"作用域变量清单"(Scoped Variable Manifest)这类 Go 结构体动态产出 JSON Schema 并随 API 响应返回前端(见 ScopedVariableRestHandler.go)。读完本文,你将掌握:如何使用 jsonschema struct tag 精确控制生成结果、如何配置 Reflector 实现展开结构体、注入 Go 注释、自定义键名与自定义类型定义,以及这套机制在 devtron 中的落地方式。
一、核心能力概述
该包能够从 Go 类型出发,通过反射直接产出符合 JSON Schema 规范的文档,其能力清单如下(与 README.md 一致):
- 支持任意复杂类型,包括
interface{}、map、slice 等; - 支持
minLength、maxLength、pattern、format等 json-schema 关键字; - 支持简单的字符串与数字枚举(enum);
- 支持通过
jsonschema_extrasstruct tag 注入自定义属性字段。
需要特别说明的是,本仓库内这份代码是原 alecthomas/jsonschema 的 fork,由 Invopop 团队维护。与上游相比发生了三处显著的不兼容变更:
- Schema 草案版本升级:上游停留在 draft-04,本版本升级为最新的 JSON Schema Draft 2020-12(版本常量定义于 reflect.go);
- Schema ID 自动生成:默认从当前 Go 包路径自动推导唯一 ID,可通过
Anonymous选项关闭; yamltag 支持被移除:官方认为这会导致若干不一致问题(详见其 issue #21 的讨论),YAML 场景推荐先转 JSON 再处理。
该库仍处于 v0 阶段(Go 约定下意味着可能发生破坏性变更),使用时建议将 go module 锁定到具体版本,本仓库即固定为 v0.7.0。
二、快速上手:从结构体到 JSON Schema
最简单的方式是直接调用包级函数 jsonschema.Reflect(v interface{}) *Schema(实现于 reflect.go)。以下结构体来自原文档示例:
type TestUser struct {
ID int `json:"id"`
Name string `json:"name" jsonschema:"title=the name,description=The name of a friend,example=joe,example=lucy,default=alex"`
Friends []int `json:"friends,omitempty" jsonschema_description:"The list of IDs, omitted when empty"`
Tags map[string]interface{} `json:"tags,omitempty" jsonschema_extras:"a=b,foo=bar,foo=bar1"`
BirthDate time.Time `json:"birth_date,omitempty" jsonschema:"oneof_required=date"`
YearOfBirth string `json:"year_of_birth,omitempty" jsonschema:"oneof_required=year"`
Metadata interface{} `json:"metadata,omitempty" jsonschema:"oneof_type=string;array"`
FavColor string `json:"fav_color,omitempty" jsonschema:"enum=red,enum=green,enum=blue"`
}
调用 jsonschema.Reflect(&TestUser{}) 得到:
{
"$schema": "http://json-schema.org/draft/2020-12/schema",
"$ref": "#/$defs/SampleUser",
"$defs": {
"SampleUser": {
"oneOf": [
{
"required": ["birth_date"],
"title": "date"
},
{
"required": ["year_of_birth"],
"title": "year"
}
],
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string",
"title": "the name",
"description": "The name of a friend",
"default": "alex",
"examples": ["joe", "lucy"]
},
"friends": {
"items": {
"type": "integer"
},
"type": "array",
"description": "The list of IDs, omitted when empty"
},
"tags": {
"type": "object",
"a": "b",
"foo": ["bar", "bar1"]
},
"birth_date": {
"type": "string",
"format": "date-time"
},
"year_of_birth": {
"type": "string"
},
"metadata": {
"oneOf": [
{
"type": "string"
},
{
"type": "array"
}
]
},
"fav_color": {
"type": "string",
"enum": ["red", "green", "blue"]
}
},
"additionalProperties": false,
"type": "object",
"required": ["id", "name"]
}
}
}
这个示例浓缩了绝大多数核心机制,逐项拆解如下(依据源码 tag 解析逻辑,见 reflect.go):
| 结构体写法 | 生成的 Schema 效果 | 底层依据 |
|---|---|---|
json:"id" 无 omitempty |
进入 required 列表 |
requiredFromJSONTags:无 omitempty 即视为必填(reflect.go) |
jsonschema:"title=...,description=...,example=...,default=..." |
生成 title、description、examples(可重复声明多个 example)、default |
genericKeywords/stringKeywords 解析(reflect.go) |
jsonschema_description:"..." |
独立生成 description 字段 |
单独读取该 tag(reflect.go) |
jsonschema_extras:"a=b,foo=bar,foo=bar1" |
注入任意自定义键 a、foo;重复键自动合并为数组 |
extraKeywords/setExtra(reflect.go) |
jsonschema:"oneof_required=date" / oneof_required=year |
在父级生成带 title 的 oneOf 分支,每个分支声明自己的 required |
oneof_required 聚合逻辑(reflect.go) |
jsonschema:"oneof_type=string;array" |
生成 oneOf 并列多个 type(以 ; 分隔) |
oneof_type 处理(reflect.go) |
jsonschema:"enum=red,enum=green,enum=blue" |
生成 enum 数组,按字段类型做字符串/整数/浮点转换 |
enum 处理(reflect.go) |
需要留意两点实现细节:一是 time.Time 会被自动映射为 "type": "string" + "format": "date-time"(见 reflect.go);二是所有结构体默认输出 "additionalProperties": false(可被 AllowAdditionalProperties 关闭)。
三、Reflector 配置行为详解
Reflector 是更精细的控制入口,所有可配置项定义在 reflect.go。下面是原文档逐一讲解的四类关键配置,以及其余重要选项的源码级说明。
3.1 ExpandedStruct:展开顶层结构体
默认情况下,顶层结构体在 $defs 中登记一个定义,根节点用 $ref 引用它。将 ExpandedStruct 设为 true 后,顶层结构体的完整定义会被直接铺开到根节点,不再自我引用。注意:传入的类型必须是 struct 类型。以原文档中的 SomeBaseType 为例:
type GrandfatherType struct {
FamilyName string `json:"family_name" jsonschema:"required"`
}
type SomeBaseType struct {
SomeBaseProperty int `json:"some_base_property"`
// 带 required 标记的私有字段、被 json:"-" 忽略的字段、被 jsonschema:"-" 忽略的字段,
// 均不会进入 required 列表,即使它们被打上了 required 标记。
somePrivateBaseProperty string `json:"i_am_private" jsonschema:"required"`
SomeIgnoredBaseProperty string `json:"-" jsonschema:"required"`
SomeSchemaIgnoredProperty string `jsonschema:"-,required"`
SomeUntaggedBaseProperty bool `jsonschema:"required"`
someUnexportedUntaggedBaseProperty bool
Grandfather GrandfatherType `json:"grand"`
}
输出:
{
"$schema": "http://json-schema.org/draft/2020-12/schema",
"required": ["some_base_property", "grand", "SomeUntaggedBaseProperty"],
"properties": {
"SomeUntaggedBaseProperty": {
"type": "boolean"
},
"grand": {
"$schema": "http://json-schema.org/draft/2020-12/schema",
"$ref": "#/definitions/GrandfatherType"
},
"some_base_property": {
"type": "integer"
}
},
"type": "object",
"$defs": {
"GrandfatherType": {
"required": ["family_name"],
"properties": {
"family_name": {
"type": "string"
}
},
"additionalProperties": false,
"type": "object"
}
}
}
该示例同时验证了字段忽略规则:被 json:"-" 或 jsonschema:"-" 标记的字段、未导出的字段一律不参与生成;而显式打了 jsonschema:"required" 的未导出字段 somePrivateBaseProperty 也不会进入 required。源码中 ignoredByJSONTags 与 ignoredByJSONSchemaTags 均以第一个 tag 是否为 - 作为判定依据(reflect.go),未导出字段则在 reflectFieldName 中直接返回空名。
3.2 使用 Go 注释生成描述(AddGoComments)
当结构体已有良好的 Go 注释时,与其在 tag 里重复写描述,不如直接复用注释。Reflector.AddGoComments(base, path string) error 会解析指定目录下的 Go 源码,构建"全限定类型/字段 → 注释"的字典(reflect.go),随后自动填充到 schema 的 description 字段;如果 tag 中已手动指定描述,则以手动值为准。
package main
// User is used as a base to provide tests for comments.
type User struct {
// Unique sequential identifier.
ID int `json:"id" jsonschema:"required"`
// Name of the user
Name string `json:"name"`
}
使用方式:
r := new(Reflector)
if err := r.AddGoComments("github.com/invopop/jsonschema", "./"); err != nil {
// deal with error
}
s := r.Reflect(&User{})
输出:
{
"$schema": "http://json-schema.org/draft/2020-12/schema",
"$ref": "#/$defs/User",
"$defs": {
"User": {
"required": ["id"],
"properties": {
"id": {
"type": "integer",
"description": "Unique sequential identifier."
},
"name": {
"type": "string",
"description": "Name of the user"
}
},
"additionalProperties": false,
"type": "object",
"description": "User is used as a base to provide tests for comments."
}
}
}
底层实现位于 comment_extractor.go:它用 go/parser 以 parser.ParseComments 模式递归遍历目录(含子目录),通过 go/ast 的 Inspect 收集 *ast.TypeSpec 与 *ast.Field 的文档注释。两个关键约束:
- 类型注释只取第一句(
go/doc的Synopsis方法),字段注释则全文保留; go/parser无法可靠推断模块的完整导入路径,所以base参数必须由调用方显式传入(例如"github.com/invopop/jsonschema")。
此外你也可以绕过文件解析,直接向 Reflector.CommentMap 填充键值对:类型键形如 github.com/invopop/jsonschema.Reflector,字段键形如 github.com/invopop/jsonschema.Reflector.DoNotReference(见 reflect.go)。
3.3 自定义键名(KeyNamer)
当 Go 结构体字段名与 API/配置文件实际使用的键名不一致时(典型如 Go 用 PascalCase、接口用 snake_case),不必在每个字段上写 json:"...",可以给 Reflector.KeyNamer 传入一个 func(string) string 做统一转换:
type User struct {
GivenName string
PasswordSalted []byte `json:"salted_password"`
}
r := new(jsonschema.Reflector)
r.KeyNamer = strcase.SnakeCase // 来自 github.com/stoewer/go-strcase
r.Reflect(&User{})
输出对比(- 为原输出,+ 为转换后):
{
"$schema": "http://json-schema.org/draft/2020-12/schema",
"$ref": "#/$defs/User",
"$defs": {
"User": {
"properties": {
- "GivenName": {
+ "given_name": {
"type": "string"
},
"salted_password": {
"type": "string",
"contentEncoding": "base64"
}
},
"additionalProperties": false,
"type": "object",
- "required": ["GivenName", "salted_password"]
+ "required": ["given_name", "salted_password"]
}
}
}
注意两点:其一,若字段带有 json:"..." tag,KeyNamer 收到的入参是 tag 值而非原始字段名(见 reflectFieldName),因此上例中带 tag 的 PasswordSalted 保持为 salted_password,未带 tag 的 GivenName 才被转成 given_name;其二,<a href="https://link.gitcode.com/i/ead0e6dec270abfd06e6ca50670218cb" target="_blank">]byte 会被映射为 "type": "string" + "contentEncoding": "base64"([reflect.go)。
3.4 自定义类型定义(JSONSchema() 方法)
有些类型实现了自定义的 MarshalJSON/UnmarshalJSON(例如把对象压缩成字符串传输),此时反射出的"object"类型并不符合实际 JSON 形态。只要让该类型实现 JSONSchema() *Schema 方法,返回值会直接作为该类型在 $defs 中的定义:
type CompactDate struct {
Year int
Month int
}
func (d *CompactDate) UnmarshalJSON(data []byte) error {
if len(data) != 9 {
return errors.New("invalid compact date length")
}
var err error
d.Year, err = strconv.Atoi(string(data[1:5]))
if err != nil {
return err
}
d.Month, err = strconv.Atoi(string(data[7:8]))
if err != nil {
return err
}
return nil
}
func (d *CompactDate) MarshalJSON() ([]byte, error) {
buf := new(bytes.Buffer)
buf.WriteByte('"')
buf.WriteString(fmt.Sprintf("%d-%02d", d.Year, d.Month))
buf.WriteByte('"')
return buf.Bytes(), nil
}
func (CompactDate) JSONSchema() *Schema {
return &Schema{
Type: "string",
Title: "Compact Date",
Description: "Short date that only includes year and month",
Pattern: "^[0-9]{4}-[0-1][0-9]$",
}
}
生成结果:
{
"$schema": "http://json-schema.org/draft/2020-12/schema",
"$ref": "#/$defs/CompactDate",
"$defs": {
"CompactDate": {
"pattern": "^[0-9]{4}-[0-1][0-9]$",
"type": "string",
"title": "Compact Date",
"description": "Short date that only includes year and month"
}
}
}
底层通过 customSchemaImpl 接口探测实现(reflect.go),在 reflectCustomSchema 中实例化类型并调用其 JSONSchema(),随后把结果注册进 $defs 并返回引用。类似地,实现 JSONSchemaExtend(*Schema) 接口的类型可以在既有 schema 生成后再做一次定制(见 reflectSchemaExtend)。
3.5 其余重要 Reflector 选项
除上述四类外,Reflector 还提供以下高频选项(字段定义见 reflect.go):
| 选项 | 作用 |
|---|---|
BaseSchemaID |
指定 schema 的基础 URI,例如 https://invopop.com/schemas,配合类型名推导出每个模型的 ID(如 /schemas/user);不设置时用类型完整包路径 https://<pkgpath> 兜底,URL 校验失败则静默忽略(reflect.go) |
Anonymous |
为 true 时隐藏自动生成的 Schema ID,产出"匿名 schema",官方标注为不推荐 |
AssignAnchor |
为 true 时在每个定义(含根 schema)写入 $anchor,值为原始结构体名(CamelCase),便于用 URI 片段引用 |
AllowAdditionalProperties |
为 true 时不再为所有结构体输出 "additionalProperties": false,允许 JSON 中出现额外键(反序列化时这些键会被丢弃) |
RequiredFromJSONSchemaTags |
默认规则是"无 json:",omitempty" 即必填";开启后改为"只有显式 jsonschema:"required" 才必填"(reflect.go) |
DoNotReference |
为 true 时不生成顶层 $defs,全部类型内联成一棵树输出(reflect.go) |
IgnoredTypes |
传入类型切片,匹配的类型在生成时被跳过,仅保留 additionalProperties 放行语义(reflect.go) |
Lookup |
func(reflect.Type) ID 回调:命中时直接用既有 schema 的 ID 引用,而不是重新内嵌定义 |
Mapper |
func(reflect.Type) *Schema 回调:为自定义 Go 类型提供完整的 schema 映射(reflect.go) |
Namer |
func(reflect.Type) string 回调:定制类型名,默认使用反射得到的 Type.Name()(reflect.go) |
AdditionalFields |
func(reflect.Type) <a href="https://link.gitcode.com/i/0c70362711e47409cf366f93ebdf3c24" target="_blank">]reflect.StructField 回调:为指定类型追加额外结构体字段参与生成([reflect.go) |
四、Schema 类型与 Draft 2020-12 的字段映射
Schema 结构体(reflect.go)几乎逐条对应 Draft 2020-12 的规范章节,这也是理解"什么 tag 能生成什么字段"的根源:
- 标识类:
$schema(Version)、$id、$anchor、$ref、$dynamicRef、$defs、$comment; - 逻辑组合:
allOf、anyOf、oneOf、not、if/then/else、dependentSchemas; - 数组约束:
prefixItems、items、contains、maxItems、minItems、uniqueItems、maxContains、minContains; - 对象约束:
properties(使用有序 map 保证字段顺序稳定)、patternProperties、additionalProperties、propertyNames、maxProperties、minProperties、required、dependentRequired; - 通用校验:
type、enum、const、multipleOf、maximum/exclusiveMaximum、minimum/exclusiveMinimum、maxLength/minLength/pattern、format; - 语义标注:
title、description、default、deprecated、readOnly、writeOnly、examples、contentEncoding、contentMediaType、contentSchema; - 扩展钩子:
Extras map<a href="https://link.gitcode.com/i/10601bfd2e0ac4556192dbd11545bc1f" target="_blank">string]interface{}承接jsonschema_extras注入的任意自定义键,序列化时被合并进最终 JSON 对象([reflect.go)。
其中 properties 使用 github.com/iancoleman/orderedmap 实现,确保输出 JSON 的字段顺序与 Go 结构体声明顺序一致,便于 diff 与阅读。
4.1 tag 关键字按类型分发
structKeywordsFromTags(reflect.go)先解析通用关键字,再根据已推断出的 type 分发到各专用解析器:
- 通用关键字(
genericKeywords):title、description、type、anchor、oneof_required、anyof_required、oneof_type、anyof_type、enum; - 字符串关键字(
stringKeywords,reflect.go):minLength、maxLength、pattern、format(仅接受date-time/email/hostname/ipv4/ipv6/uri/uuid)、readOnly、writeOnly、default、example; - 数值关键字(
numbericKeywords,reflect.go):multipleOf、minimum、maximum、exclusiveMaximum、exclusiveMinimum、default、example; - 数组关键字(
arrayKeywords,reflect.go):minItems、maxItems、uniqueItems、default(可聚合为数组默认值)、enum(作用于items)、format(作用于items); - 布尔关键字(
booleanKeywords,reflect.go):default(解析"true"/"false")。
一个容易被忽略的细节:tag 字符串按未转义逗号切分(splitOnUnescapedCommas,reflect.go),因此当 pattern 等值本身含逗号时,可用反斜杠 \, 转义防止误切分。
4.2 内建特殊类型的映射
反射过程中有一组内建类型映射(reflect.go):
| Go 类型 | 生成的 Schema |
|---|---|
time.Time |
"type": "string" + "format": "date-time" |
net.IP |
"type": "string" + "format": "ipv4" |
url.URL |
"type": "string" + "format": "uri" |
[]byte(json.RawMessage 除外) |
"type": "string" + "contentEncoding": "base64" |
json.RawMessage |
直接返回空 schema(true),不做约束 |
实现 protoEnum 接口的 protobuf 枚举 |
oneOf 并列 string 与 integer(jsonpb 的编解码兼容两种形态) |
| 整型家族 | "type": "integer" |
| 浮点家族 | "type": "number" |
bool |
"type": "boolean" |
string |
"type": "string" |
| 数组/切片 | "type": "array" + items;定长数组(reflect.Array)额外输出 minItems/maxItems 为固定长度 |
| map | "type": "object";整数键映射为 patternProperties: "^[0-9]+$",其余键映射为 ".*",元素为 interface{} 时不做 pattern 约束 |
五、布尔型 Schema 与序列化行为
JSON Schema 允许把 schema 写作布尔字面量(true 表示"任意值都合法",false 表示"拒绝一切")。本库通过 TrueSchema/FalseSchema 两个预定义常量支持(reflect.go),并实现了一对对称的钩子:
UnmarshalJSON(reflect.go):输入恰好为true/false时解析为布尔 schema,否则按普通对象解析;MarshalJSON(reflect.go):布尔 schema 原样输出true/false;空 schema 也输出true(避免无意义对象);带Extras时把扩展键合并进输出对象。
六、在 devtron 中的实际应用
该库在 devtron 中并非只是"躺"在 vendor 里,而是真实服务于 API 层。仓库通过 SchemaUtils.go 封装了一个泛型入口:
package util
import (
"encoding/json"
"github.com/invopop/jsonschema"
)
func GetSchemaFromTypeT any (string, error) {
schema := jsonschema.Reflect(t)
schemaData, err := json.MarshalIndent(schema, "", " ")
if err != nil {
return "", err
}
return string(schemaData), nil
}
该函数借助 Go 1.18+ 泛型,将"反射生成 + 缩进格式化"收敛为一行调用,调用方无需关心 Reflector 细节。实际消费点在作用域变量的查询接口 ScopedVariableRestHandler.go:服务端在 GetJsonForVariables 中取出变量清单后,调用 util.GetSchemaFromType(models.ScopedVariableManifest{}) 生成该清单类型的 JSON Schema,与 Manifest 数据一同装入响应体返回给前端:
schema, err := util.GetSchemaFromType(models.ScopedVariableManifest{})
if err != nil {
common.WriteJsonResp(w, err, "schema cannot be generated for manifest type", http.StatusInternalServerError)
return
}
jsonResponse := JsonResponse{
JsonSchema: schema,
}
这正是"用一份 Go 类型定义同时约束服务端数据与前端表单/校验器"的典型场景:前端拿到 JsonSchema 即可渲染动态表单或执行客户端校验,而 schema 的合法性由 devtron 的全局配置(如 RBAC 中的超级管理员校验,见同文件 L178-L182)与类型系统共同保证。
七、YAML 场景的处理建议
由于本版本已移除 yaml tag 支持,若业务数据以 YAML 形式存在(例如 Helm values、Kubernetes 清单),官方给出的推荐路径是:先用 YAML-to-JSON 转换库把 YAML 转成 JSON,再走本库生成 schema。Invopop 提供了配套的 invopop/yaml 库让这一转换变得"trivial"。devtron 本身重度依赖 Helm Chart(仓库 contrib-chart 与 scripts/devtron-reference-helm-charts 即存放了大量 Chart 模板),凡是需要为这类 YAML 化的配置生成校验 schema 的场景,都应遵循"先转 JSON 再反射"的约定,而不是依赖被移除的 yaml tag。
八、使用注意事项小结
- 锁定版本:项目仍处于 v0 语义版本阶段,破坏性变更随时可能发生,务必像本仓库一样在 go.mod 中固定版本(本仓库为
v0.7.0); - 必填语义默认来源:默认"无
omitempty即必填",若希望改为显式jsonschema:"required"声明,请开启RequiredFromJSONSchemaTags; - 字段忽略规则:
json:"-"与jsonschema:"-"都会让字段彻底退出生成;未导出字段天然不参与; - 自定义类型优先:凡是实现
JSONSchema() *Schema的类型,反射会优先采用你的自定义定义,这比在外部写Mapper更内聚; - Schema ID 默认自动推导:以类型完整包路径为基址、类型名转 kebab-case 拼接(
ToSnakeCase实现见 utils.go),如需统一 ID 空间请设置BaseSchemaID,需要匿名化则设Anonymous。
综上,invopop/jsonschema 用一套紧凑的 struct tag 语法加若干 Reflector 开关,覆盖了从"一行调用出 schema"到"精细控制每个关键字"的全谱系需求;devtron 将其封装为泛型 GetSchemaFromType 并运用于作用域变量接口,是"类型即契约、契约即校验"这一理念在 Kubernetes 应用交付平台中的一次简洁落地。若要深入阅读实现,推荐直接从 reflect.go 的 Reflector 与 Schema 两个类型开始。