MCPcopy Create free account
hub / github.com/astercloud/aster / structToSchema

Method structToSchema

pkg/structured/schema.go:46–140  ·  view source on GitHub ↗

structToSchema 将 struct 类型转换为 JSON Schema

(typ reflect.Type)

Source from the content-addressed store, hash-verified

44
45// structToSchema 将 struct 类型转换为 JSON Schema
46func (g *SchemaGenerator) structToSchema(typ reflect.Type) (map[string]any, error) {
47 schema := map[string]any{
48 "type": "object",
49 "properties": make(map[string]any),
50 }
51
52 var required []string
53 properties := schema["properties"].(map[string]any)
54
55 for i := 0; i < typ.NumField(); i++ {
56 field := typ.Field(i)
57
58 // 跳过未导出的字段
59 if !field.IsExported() {
60 continue
61 }
62
63 // 获取 JSON 标签
64 jsonTag := field.Tag.Get("json")
65 if jsonTag == "-" {
66 continue // 跳过标记为 "-" 的字段
67 }
68
69 // 解析 JSON 标签
70 fieldName := field.Name
71 omitEmpty := false
72 if jsonTag != "" {
73 parts := strings.Split(jsonTag, ",")
74 if parts[0] != "" {
75 fieldName = parts[0]
76 }
77 for _, part := range parts[1:] {
78 if part == "omitempty" {
79 omitEmpty = true
80 }
81 }
82 }
83
84 // 生成字段 Schema
85 fieldSchema, err := g.typeToSchema(field.Type)
86 if err != nil {
87 return nil, fmt.Errorf("field %s: %w", fieldName, err)
88 }
89
90 // 添加描述
91 if desc := field.Tag.Get("description"); desc != "" {
92 fieldSchema["description"] = desc
93 }
94
95 // 添加枚举
96 if enumTag := field.Tag.Get("enum"); enumTag != "" {
97 values := strings.Split(enumTag, ",")
98 fieldSchema["enum"] = values
99 }
100
101 // 添加数字范围约束
102 if field.Type.Kind() == reflect.Int || field.Type.Kind() == reflect.Int64 ||
103 field.Type.Kind() == reflect.Float64 {

Callers 2

FromStructMethod · 0.95
typeToSchemaMethod · 0.95

Calls 3

typeToSchemaMethod · 0.95
GetMethod · 0.65
KindMethod · 0.65

Tested by

no test coverage detected