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

Method typeToSchema

pkg/structured/schema.go:143–195  ·  view source on GitHub ↗

typeToSchema 将 Go 类型转换为 JSON Schema 类型

(typ reflect.Type)

Source from the content-addressed store, hash-verified

141
142// typeToSchema 将 Go 类型转换为 JSON Schema 类型
143func (g *SchemaGenerator) typeToSchema(typ reflect.Type) (map[string]any, error) {
144 // 处理指针类型
145 if typ.Kind() == reflect.Ptr {
146 return g.typeToSchema(typ.Elem())
147 }
148
149 schema := make(map[string]any)
150
151 switch typ.Kind() {
152 case reflect.String:
153 schema["type"] = "string"
154
155 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
156 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
157 schema["type"] = "integer"
158
159 case reflect.Float32, reflect.Float64:
160 schema["type"] = "number"
161
162 case reflect.Bool:
163 schema["type"] = "boolean"
164
165 case reflect.Slice, reflect.Array:
166 schema["type"] = "array"
167 itemSchema, err := g.typeToSchema(typ.Elem())
168 if err != nil {
169 return nil, fmt.Errorf("array element: %w", err)
170 }
171 schema["items"] = itemSchema
172
173 case reflect.Map:
174 schema["type"] = "object"
175 if typ.Key().Kind() != reflect.String {
176 return nil, fmt.Errorf("map key must be string, got %v", typ.Key().Kind())
177 }
178 // 对于 map[string]any,使用 additionalProperties
179 schema["additionalProperties"] = true
180
181 case reflect.Struct:
182 // 嵌套结构体
183 return g.structToSchema(typ)
184
185 case reflect.Interface:
186 // 对于 interface{} 或 any,允许任何类型
187 // 不指定 type 字段,表示可以是任何 JSON 类型
188 return schema, nil
189
190 default:
191 return nil, fmt.Errorf("unsupported type: %v", typ.Kind())
192 }
193
194 return schema, nil
195}
196
197// Validate 验证 Schema 的基本有效性
198func (g *SchemaGenerator) Validate(schema map[string]any) error {

Callers 1

structToSchemaMethod · 0.95

Calls 2

structToSchemaMethod · 0.95
KindMethod · 0.65

Tested by

no test coverage detected