Golang结构体生成Schema工具
请问有没有推荐的工具可以将Golang结构体自动生成数据库Schema?最近在开发项目时需要频繁根据结构体定义来创建数据库表结构,手动编写SQL比较耗时。希望能找到一款支持自动转换的工具,最好能兼容主流数据库如MySQL/PostgreSQL,并且支持自定义字段类型映射和索引定义。如果有实际使用经验的朋友,能否分享一下工具的使用体验和注意事项?
2 回复
推荐使用go-swagger或json-schema-generator。前者可基于结构体注释生成OpenAPI Schema,后者直接转换结构体为JSON Schema。安装简单,适合API文档生成和数据验证。
更多关于Golang结构体生成Schema工具的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Golang中,可以使用以下工具将结构体转换为JSON Schema或其他格式的Schema:
1. gojsonschema
package main
import (
"encoding/json"
"fmt"
"github.com/xeipuuv/gojsonschema"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age,omitempty"`
Active bool `json:"active"`
}
func main() {
// 手动创建JSON Schema
schema := map[string]interface{}{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": map[string]interface{}{
"id": map[string]interface{}{
"type": "integer",
},
"name": map[string]interface{}{
"type": "string",
},
"email": map[string]interface{}{
"type": "string",
"format": "email",
},
"age": map[string]interface{}{
"type": "integer",
"minimum": 0,
},
"active": map[string]interface{}{
"type": "boolean",
},
},
"required": []string{"id", "name", "email", "active"},
}
schemaJSON, _ := json.MarshalIndent(schema, "", " ")
fmt.Println(string(schemaJSON))
}
2. 使用反射自动生成
package main
import (
"encoding/json"
"fmt"
"reflect"
)
func generateSchemaFromStruct(obj interface{}) map[string]interface{} {
t := reflect.TypeOf(obj)
schema := map[string]interface{}{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": map[string]interface{}{},
"required": []string{},
}
properties := schema["properties"].(map[string]interface{})
required := schema["required"].([]string)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
jsonTag := field.Tag.Get("json")
if jsonTag == "" || jsonTag == "-" {
continue
}
fieldName := jsonTag
if fieldName == "" {
fieldName = field.Name
}
fieldType := getJSONType(field.Type)
prop := map[string]interface{}{
"type": fieldType,
}
// 处理omitempty
if !isOmitEmpty(jsonTag) {
required = append(required, fieldName)
}
properties[fieldName] = prop
}
schema["required"] = required
return schema
}
func getJSONType(fieldType reflect.Type) string {
switch fieldType.Kind() {
case reflect.String:
return "string"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return "integer"
case reflect.Float32, reflect.Float64:
return "number"
case reflect.Bool:
return "boolean"
default:
return "string"
}
}
func isOmitEmpty(tag string) bool {
// 简化处理,实际应该解析tag
return len(tag) > 0
}
3. 第三方库推荐
- github.com/invopop/jsonschema: 功能完善的JSON Schema生成器
- github.com/alecthomas/jsonschema: 基于反射的Schema生成
- github.com/santhosh-tekuri/jsonschema: 支持从Go类型生成Schema
这些工具可以帮助你从Go结构体自动生成对应的Schema定义,适用于API文档生成、数据验证等场景。

