feat(http): 增加 OpenAPI 契约生成能力
Verify / verify (push) Canceled after 0s

从已注册 Controller 的 Form、返回类型及字段声明生成请求、
响应和校验约束,补充显式安全方案与操作级覆盖。
复用 kin-openapi 原生类型与校验,保留合并绑定语义,
为原生路由和无法等价映射的声明提供补充入口。

同步接入指南、迁移边界和可独立运行的契约导出示例。
验证:make verify、make race-check 及实际示例导出通过。
This commit is contained in:
zhangdeman committed 2026-11-26 21:10:02 -08:00
1 parent e901a1e964
commit b4a21f53ac
13 files changed
+1304 -8

No files matched your search

+223
View File
@@ -0,0 +1,223 @@
package http
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"reflect"
"strings"
"git.zhangdeman.cn/github/ginframework/http/request"
failure "git.zhangdeman.cn/github/ginframework/internal/failure"
"github.com/getkin/kin-openapi/openapi3"
)
const (
openAPIVersion = "3.0.3"
publicSecurity = "-"
)
// OpenAPIOptions 是一次文档生成的数据及显式扩展点,不参与运行时认证。
type OpenAPIOptions struct {
Title string `json:"title" dc:"必填的 API 文档标题"`
Version string `json:"version" dc:"必填的应用 API 版本,不是 OpenAPI 规范版本"`
Servers openapi3.Servers `json:"servers,omitempty" dc:"可选的部署入口列表"`
SecuritySchemes openapi3.SecuritySchemes `json:"security_schemes,omitempty" dc:"原生安全方案声明,不包含真实凭据"`
Security openapi3.SecurityRequirements `json:"security,omitempty" dc:"默认安全要求;数组为或,同一对象中的多个方案为且"`
Customize func(Metadata, *openapi3.Operation) error `json:"-" dc:"可选的单路由契约补充,处理原生响应、复杂约束或 OAuth scope"`
}
// OpenAPI 从已成功注册的路由生成独立的 OpenAPI 3.0.3 文档。
// 入参:options 为标题、版本、安全声明及可选操作补充函数。
// 返回:已解析引用并通过规范校验的原生文档;声明、类型或补充错误返回 nil 与原因链。
// 副作用:只读取路由快照,不冻结注册、不发布端点、不执行 Controller 或认证中间件。
func (s *Server) OpenAPI(options OpenAPIOptions) (*openapi3.T, error) {
if strings.TrimSpace(options.Title) == "" || strings.TrimSpace(options.Version) == "" {
return nil, failure.Wrap(codeOpenAPIOptions, "validate OpenAPI options failed", errors.New("title and version are required"))
}
s.lock.Lock()
routes := append([]route(nil), s.routes...)
s.lock.Unlock()
// 先复制调用方数据,库的生成和校验不修改应用拥有的安全方案。
doc, err := loadOpenAPI(&openapi3.T{OpenAPI: openAPIVersion, Info: &openapi3.Info{Title: options.Title, Version: options.Version}, Paths: openapi3.NewPaths(), Components: &openapi3.Components{Schemas: openapi3.Schemas{}, SecuritySchemes: options.SecuritySchemes}, Security: options.Security, Servers: options.Servers})
if err != nil {
return nil, failure.Wrap(codeOpenAPICopy, "copy OpenAPI options failed", err)
}
if doc.Components == nil {
doc.Components = &openapi3.Components{}
}
doc.Components.Schemas = openapi3.Schemas{}
for _, item := range routes {
path, parameters, pathErr := openAPIPath(item.meta.Path)
if pathErr != nil {
return nil, failure.Wrap(codeOpenAPIPath, "convert OpenAPI route path failed", pathErr)
}
if !strings.Contains(" GET PUT POST DELETE OPTIONS HEAD PATCH TRACE ", " "+item.meta.Method+" ") {
return nil, failure.Wrap(codeOpenAPIMethod, "convert OpenAPI route method failed", errors.New("method has no OpenAPI 3.0 operation"))
}
operation, operationErr := s.openAPIOperation(item, doc.Components.Schemas, parameters)
if operationErr != nil {
return nil, operationErr
}
if item.security != "" {
requirements := openapi3.SecurityRequirements{}
if item.security != publicSecurity {
requirement := openapi3.SecurityRequirement{}
for _, name := range strings.Split(item.security, ",") {
name = strings.TrimSpace(name)
if name == "" {
return nil, failure.Wrap(codeOpenAPISecurity, "validate route security declaration failed", errors.New("empty security scheme name"))
}
requirement[name] = []string{}
}
requirements = append(requirements, requirement)
}
operation.Security = &requirements
}
if options.Customize != nil {
if err = options.Customize(item.meta, operation); err != nil {
return nil, failure.Wrap(codeOpenAPICustomize, "customize OpenAPI operation failed", err)
}
}
entry := doc.Paths.Value(path)
if entry == nil {
entry = &openapi3.PathItem{}
doc.Paths.Set(path, entry)
}
if entry.GetOperation(item.meta.Method) != nil {
return nil, failure.Wrap(codeOpenAPIDuplicate, "validate OpenAPI route uniqueness failed", errors.New("multiple Gin routes normalize to one operation"))
}
entry.SetOperation(item.meta.Method, operation)
}
// 经过序列化边界重新解析引用,也验证应用补充后的真实输出。
doc, err = loadOpenAPI(doc)
if err == nil {
err = failure.Wrap(codeOpenAPISecurity, "validate OpenAPI security references failed", validateSecurity(doc))
}
if err == nil {
err = doc.Validate(context.Background())
}
if err != nil {
return nil, failure.Wrap(codeOpenAPIValidate, "validate generated OpenAPI document failed", err)
}
return doc, nil
}
// loadOpenAPI 通过原生加载器复制文档并解析内部引用,禁止加载外部引用。
// 入参:doc 为尚未对外发布的文档;返回独立对象或序列化/引用错误。
func loadOpenAPI(doc *openapi3.T) (*openapi3.T, error) {
raw, err := json.Marshal(doc)
if err != nil {
return nil, err
}
return openapi3.NewLoader().LoadFromData(raw)
}
// openAPIOperation 根据普通路由的静态签名生成参数及协议响应。
// 入参:item 为注册快照,schemas 为本次组件集合,paths 为路径占位参数。
// 返回:原生路由仅返回明确的未推断标记,供应用显式补充。
func (s *Server) openAPIOperation(item route, schemas openapi3.Schemas, paths openapi3.Parameters) (*openapi3.Operation, error) {
op := &openapi3.Operation{Summary: item.meta.Summary, Parameters: paths, Responses: openapi3.NewResponses()}
if item.meta.Tag != "" {
op.Tags = []string{item.meta.Tag}
}
if item.input == nil {
op.Extensions = map[string]any{"x-gin-native": true}
op.Responses.Set("default", &openapi3.ResponseRef{Value: openapi3.NewResponse().WithDescription("Native handler response; application contract required")})
return op, nil
}
if err := s.openAPIRequest(op, item, schemas); err != nil {
return nil, failure.Wrap(codeOpenAPISchema, "generate OpenAPI request schema failed", err)
}
output, err := responseContractSchema(item.output, schemas)
if err != nil {
return nil, failure.Wrap(codeOpenAPIResponse, "generate OpenAPI response schema failed", err)
}
envelope, err := responseContractSchema(reflect.TypeOf(Envelope{}), schemas)
if err != nil {
return nil, failure.Wrap(codeOpenAPIResponse, "generate OpenAPI envelope schema failed", err)
}
envelope.Value.Properties["data"] = output
envelope.Value.Required = []string{"code", "message", "data", "trace_id", "cost_ms"}
envelope.Value.Properties["code"].Value.Enum = []any{s.config.SuccessCode}
op.Responses.Set("200", jsonContract("Successful response", envelope))
for _, status := range []int{400, 413, 415, 500, 504} {
errorEnvelope, schemaErr := responseContractSchema(reflect.TypeOf(Envelope{}), schemas)
if schemaErr != nil {
return nil, failure.Wrap(codeOpenAPIResponse, "generate OpenAPI error schema failed", schemaErr)
}
if status == 400 {
details, detailErr := responseContractSchema(reflect.TypeOf(request.ValidationDetails{}), schemas)
if detailErr != nil {
return nil, failure.Wrap(codeOpenAPIResponse, "generate OpenAPI validation schema failed", detailErr)
}
details.Value.Nullable = true
errorEnvelope.Value.Properties["data"] = details
}
op.Responses.Set(fmt.Sprint(status), jsonContract(http.StatusText(status), errorEnvelope))
}
if item.meta.Method == http.MethodHead {
for _, response := range op.Responses.Map() {
response.Value.Content = nil
}
}
return op, nil
}
// jsonContract 构造 JSON 响应声明;入参为安全描述和结构引用,返回原生响应。
func jsonContract(description string, schema *openapi3.SchemaRef) *openapi3.ResponseRef {
return &openapi3.ResponseRef{Value: openapi3.NewResponse().WithDescription(description).WithContent(openapi3.Content{"application/json": &openapi3.MediaType{Schema: schema}})}
}
// openAPIPath 转换 Gin 占位符并保留 catch-all 的扩展声明。
// 入参:path 为最终路径;返回规范路径、必填字符串占位参数或不支持的路径错误。
func openAPIPath(path string) (string, openapi3.Parameters, error) {
parts := strings.Split(path, "/")
parameters := openapi3.Parameters{}
for index, part := range parts {
if strings.HasPrefix(part, ":") || strings.HasPrefix(part, "*") {
name := part[1:]
if name == "" || strings.ContainsAny(name, "{}") {
return "", nil, errors.New("invalid Gin path parameter")
}
parameter := openapi3.NewPathParameter(name).WithSchema(openapi3.NewStringSchema())
if part[0] == '*' {
parameter.Extensions = map[string]any{"x-gin-catch-all": true}
}
parameters = append(parameters, &openapi3.ParameterRef{Value: parameter})
parts[index] = "{" + name + "}"
} else if strings.ContainsAny(part, ":*{}") {
return "", nil, errors.New("embedded path parameters need an application contract")
}
}
return strings.Join(parts, "/"), parameters, nil
}
// validateSecurity 拒绝拼错或缺失的方案引用,防止文档出现无定义认证要求。
// 入参:doc 为完整文档;返回不存在的方案或非 OAuth scope 声明错误。
func validateSecurity(doc *openapi3.T) error {
all := []openapi3.SecurityRequirements{doc.Security}
for _, path := range doc.Paths.Map() {
for _, op := range path.Operations() {
if op.Security != nil {
all = append(all, *op.Security)
}
}
}
for _, requirements := range all {
for _, requirement := range requirements {
for name, scopes := range requirement {
scheme := doc.Components.SecuritySchemes[name]
if scheme == nil || scheme.Value == nil {
return fmt.Errorf("undefined security scheme %q", name)
}
if len(scopes) != 0 && scheme.Value.Type != "oauth2" && scheme.Value.Type != "openIdConnect" {
return errors.New("scopes require OAuth2 or OpenID Connect")
}
}
}
}
return nil
}
+196
View File
@@ -0,0 +1,196 @@
package http
import (
"mime/multipart"
"net/http"
"reflect"
"strings"
"github.com/getkin/kin-openapi/openapi3"
)
// openAPIRequest 从 Form 描述路径、查询及三类正文,并隐藏由可信注入拥有的顶层字段。
// 入参:op 为本次操作,item 为路由快照,schemas 为本次组件;返回 Schema 生成错误。
func (s *Server) openAPIRequest(op *openapi3.Operation, item route, schemas openapi3.Schemas) error {
fields := contractInputFields(item.input, map[reflect.Type]bool{})
hiddenGo, hiddenJSON := map[string]bool{}, map[string]bool{}
for name := range s.options.TrustedFields {
field, exists := item.input.FieldByName(name)
if !exists {
continue
}
if field.Anonymous && strings.SplitN(field.Tag.Get("json"), ",", 2)[0] == "" {
for _, child := range contractInputFields(field.Type, map[reflect.Type]bool{}) {
hiddenGo[child.Name] = true
hiddenJSON[contractFieldName(child, "json")] = true
}
} else {
hiddenGo[field.Name] = true
hiddenJSON[contractFieldName(field, "json")] = true
}
}
bodyMethod := item.meta.Method == http.MethodPost || item.meta.Method == http.MethodPut || item.meta.Method == http.MethodPatch || item.meta.Method == http.MethodDelete
formBody := openapi3.NewObjectSchema()
urlBody := openapi3.NewObjectSchema()
for _, field := range fields {
if hiddenGo[field.Name] {
continue
}
uri := strings.SplitN(field.Tag.Get("uri"), ",", 2)[0]
if uri != "" && uri != "-" {
for _, parameter := range op.Parameters {
if parameter.Value.Name == uri {
schema, err := contractFieldSchema(field, schemas)
if err != nil {
return err
}
parameter.Value.Schema = schema
parameter.Value.Description = field.Tag.Get("dc")
}
}
}
name := contractFieldName(field, "form")
if name == "-" || (uri != "" && field.Tag.Get("form") == "") {
continue
}
file := contractFileSchema(field.Type)
schema := file
if schema == nil {
var (
err error
)
schema, err = contractFieldSchema(field, schemas)
if err != nil {
return err
}
}
formBody.Properties[name] = schema
if file != nil {
file.Value.Description = field.Tag.Get("dc")
applyContractRules(file.Value, field.Tag.Get("binding"))
continue
}
urlBody.Properties[name] = schema
parameter := openapi3.NewQueryParameter(name)
parameter.Description, parameter.Schema = field.Tag.Get("dc"), schema
parameter.Required = !bodyMethod && requiredContractField(field) && uri == ""
if schema.Value != nil && (schema.Value.Type.Is("object")) {
// Gin 对 Query 中的结构体和 Map 使用 JSON 字符串解码。
parameter.Schema = nil
parameter.Content = openapi3.Content{"application/json": &openapi3.MediaType{Schema: schema}}
} else if schema.Value != nil && schema.Value.Type.Is("array") {
explode := true
parameter.Style, parameter.Explode = "form", &explode
switch field.Tag.Get("collection_format") {
case "csv":
*parameter.Explode = false
case "ssv":
parameter.Style = "spaceDelimited"
*parameter.Explode = false
case "pipes":
parameter.Style = "pipeDelimited"
*parameter.Explode = false
}
}
op.Parameters = append(op.Parameters, &openapi3.ParameterRef{Value: parameter})
}
if !bodyMethod {
return nil
}
body, err := filteredContractSchema(item.input, schemas, hiddenJSON, false)
if err != nil {
return err
}
if len(body.Value.Required) > 0 {
if body.Value.Extensions == nil {
body.Value.Extensions = map[string]any{}
}
publicRequired := []string{}
for _, name := range body.Value.Required {
if body.Value.Properties[name] != nil {
publicRequired = append(publicRequired, name)
}
}
body.Value.Extensions["x-gin-required-after-merge"] = publicRequired
body.Value.Required = nil
}
content := openapi3.Content{"application/json": &openapi3.MediaType{Schema: body}}
if len(formBody.Properties) > 0 {
content["multipart/form-data"] = &openapi3.MediaType{Schema: formBody.NewRef()}
}
if len(urlBody.Properties) > 0 {
content["application/x-www-form-urlencoded"] = &openapi3.MediaType{Schema: urlBody.NewRef()}
}
op.RequestBody = &openapi3.RequestBodyRef{Value: &openapi3.RequestBody{Description: "URI → Query → Body merged before defaults, trusted injection and validation", Content: content}}
return nil
}
// contractInputFields 展开无 form/uri/json 命名的匿名输入,跳过 Meta 和不可导出字段。
// 入参:t 为 Form,visiting 为当前递归路径;返回公开字段清单,不修改业务类型。
func contractInputFields(t reflect.Type, visiting map[reflect.Type]bool) []reflect.StructField {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
fields := []reflect.StructField{}
if t.Kind() != reflect.Struct || visiting[t] {
return fields
}
visiting[t] = true
defer delete(visiting, t)
for index := 0; index < t.NumField(); index++ {
field := t.Field(index)
if field.Type == reflect.TypeOf(Meta{}) {
continue
}
if field.Anonymous && field.Tag.Get("json") == "" && field.Tag.Get("form") == "" && field.Tag.Get("uri") == "" {
fields = append(fields, contractInputFields(field.Type, visiting)...)
continue
}
if field.PkgPath == "" {
fields = append(fields, field)
}
}
return fields
}
// contractFieldSchema 生成绑定字段及字段本身的约束。
// 入参:field 为原字段声明,schemas 为本次组件;返回带说明及校验声明的独立引用。
func contractFieldSchema(field reflect.StructField, schemas openapi3.Schemas) (*openapi3.SchemaRef, error) {
schema, err := contractSchema(field.Type, schemas)
if err != nil {
return nil, err
}
t := field.Type
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 {
item, itemErr := contractSchema(t.Elem(), schemas)
if itemErr != nil {
return nil, itemErr
}
schema = openapi3.NewArraySchema().NewRef()
schema.Value.Items = item
}
if schema.Value != nil {
if !schema.Value.Type.Is("object") {
schema.Value.Nullable = false
}
schema.Value.Description = field.Tag.Get("dc")
applyContractRules(schema.Value, field.Tag.Get("binding"))
setContractDefault(schema.Value, field.Tag)
}
return schema, nil
}
// contractFileSchema 将绑定器支持的上传类型映射为 multipart 二进制字段。
// 入参:t 为字段类型;返回文件结构或 nil 表示普通字段。
func contractFileSchema(t reflect.Type) *openapi3.SchemaRef {
if t == reflect.TypeOf(multipart.FileHeader{}) || t == reflect.TypeOf((*multipart.FileHeader)(nil)) {
return openapi3.NewStringSchema().WithFormat("binary").NewRef()
}
if t == reflect.TypeOf([]*multipart.FileHeader{}) {
return openapi3.NewArraySchema().WithItems(openapi3.NewStringSchema().WithFormat("binary")).NewRef()
}
return nil
}
+390
View File
@@ -0,0 +1,390 @@
package http
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3gen"
)
var (
contractEnumTokens = regexp.MustCompile(`'[^']*'|\S+`)
jsonMarshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
)
// contractSchema 复用原生类型生成器,只补充 dc 和 binding 的静态语义。
// 入参:t 为 DTO 类型,schemas 为本次生成拥有的组件集合;返回 Schema 或不支持的类型错误。
func contractSchema(t reflect.Type, schemas openapi3.Schemas) (*openapi3.SchemaRef, error) {
return filteredContractSchema(t, schemas, nil, false)
}
// responseContractSchema 按序列化存在性生成响应,不将输入 binding 当作响应校验。
// 入参:t 为响应类型,schemas 为组件集合;返回独立响应结构或类型错误。
func responseContractSchema(t reflect.Type, schemas openapi3.Schemas) (*openapi3.SchemaRef, error) {
return filteredContractSchema(t, schemas, nil, true)
}
// filteredContractSchema 在生成根节点时排除可信注入属性,循环引用的组件也保留相同边界。
// 入参:t 为 DTO,schemas 为组件集合,hidden 为根节点隐藏字段,response 为响应方向。
// 返回:与运行时 JSON 序列化对应的结构或错误,不保留输入对象。
func filteredContractSchema(t reflect.Type, schemas openapi3.Schemas, hidden map[string]bool, response bool) (*openapi3.SchemaRef, error) {
if err := checkContractReferenceTypes(t, map[reflect.Type]bool{}); err != nil {
return nil, err
}
if t.Kind() == reflect.Interface {
return openapi3.NewSchema().WithNullable().NewRef(), nil
}
local := openapi3.Schemas{}
customizer := contractCustomizer(response)
ref, err := openapi3gen.NewSchemaRefForValue(reflect.New(t).Elem().Interface(), local,
openapi3gen.UseAllExportedFields(), openapi3gen.CreateFieldNameGenerator(func(field reflect.StructField, _ string) string { return contractFieldName(field, "json") }), openapi3gen.SchemaCustomizer(func(name string, t reflect.Type, tag reflect.StructTag, schema *openapi3.Schema) error {
if err := customizer(name, t, tag, schema); err != nil {
return err
}
if name == "_root" {
for key := range hidden {
delete(schema.Properties, key)
}
required := []string{}
for _, key := range schema.Required {
if !hidden[key] {
required = append(required, key)
}
}
schema.Required = required
}
return nil
}))
if err != nil {
return nil, err
}
if ref == nil {
return nil, fmt.Errorf("unsupported contract type %s", t)
}
for name, component := range local {
if previous := schemas[name]; previous != nil {
left, leftErr := json.Marshal(previous)
right, rightErr := json.Marshal(component)
if leftErr != nil || rightErr != nil || !bytes.Equal(left, right) {
return nil, fmt.Errorf("conflicting recursive schema name %q", name)
}
}
schemas[name] = component
}
if ref.Value != nil && (t.Kind() == reflect.Ptr || t.Kind() == reflect.Map || t.Kind() == reflect.Slice) {
copy := *ref.Value
ref.Value = &copy
ref.Value.Nullable = true
}
return ref, nil
}
// checkContractReferenceTypes 拒绝原生生成器会作为结构体 Ref 对象处理的标量别名。
// 入参:t 为 DTO 图类型,visited 防止循环重复;返回明确的不支持错误,避免依赖反射 panic。
func checkContractReferenceTypes(t reflect.Type, visited map[reflect.Type]bool) error {
if visited[t] {
return nil
}
visited[t] = true
if t.Kind() != reflect.Struct && strings.HasSuffix(t.Name(), "Ref") {
return fmt.Errorf("non-struct reference-named DTO type %s requires a plain contract type", t)
}
if t.Implements(jsonMarshalerType) || reflect.PointerTo(t).Implements(jsonMarshalerType) {
return nil
}
switch t.Kind() {
case reflect.Ptr, reflect.Slice, reflect.Array, reflect.Map:
return checkContractReferenceTypes(t.Elem(), visited)
case reflect.Struct:
for index := 0; index < t.NumField(); index++ {
field := t.Field(index)
if field.PkgPath != "" && !field.Anonymous || strings.SplitN(field.Tag.Get("json"), ",", 2)[0] == "-" {
continue
}
if err := checkContractReferenceTypes(field.Type, visited); err != nil {
return err
}
}
}
return nil
}
// contractCustomizer 按方向补充字段语义,防止切片 tag 错误应用到元素。
// 入参:response 表示响应序列化方向;返回原生回调,Meta 被排除、复杂序列化被标记。
func contractCustomizer(response bool) openapi3gen.SchemaCustomizerFn {
return func(name string, t reflect.Type, tag reflect.StructTag, schema *openapi3.Schema) error {
if t == reflect.TypeOf(Meta{}) {
return &openapi3gen.ExcludeSchemaSentinel{}
}
if t != reflect.TypeOf(time.Time{}) && (t.Implements(jsonMarshalerType) || reflect.PointerTo(t).Implements(jsonMarshalerType)) {
*schema = openapi3.Schema{Extensions: map[string]any{"x-gin-custom-json": true}}
return nil
}
if t.Kind() == reflect.Slice || t.Kind() == reflect.Map {
schema.Nullable = true
}
if t.Kind() == reflect.Array {
schema.Extensions = map[string]any{"x-gin-schema-unresolved": "fixed array; application schema required"}
}
if t.Kind() != reflect.Struct || !schema.Type.Is("object") {
return nil
}
for _, field := range reflect.VisibleFields(t) {
if field.PkgPath != "" || field.Type == reflect.TypeOf(Meta{}) {
continue
}
label := contractFieldName(field, "json")
property := schema.Properties[label]
if property == nil || property.Value == nil {
continue
}
property = nullableContractRef(field.Type, property)
schema.Properties[label] = property
property.Value.Description = field.Tag.Get("dc")
binding := field.Tag.Get("binding")
if !response && requiredContractField(field) || response && responseFieldRequired(t, field) {
schema.Required = append(schema.Required, label)
}
valueType := field.Type
for valueType.Kind() == reflect.Ptr {
valueType = valueType.Elem()
}
quotedScalar := valueType.Kind() == reflect.Bool || valueType.Kind() >= reflect.Int && valueType.Kind() <= reflect.Float64 || valueType.Kind() == reflect.String
if quotedScalar && property.Value.Extensions["x-gin-custom-json"] != true && strings.Contains(","+field.Tag.Get("json")+",", ",string,") {
nullable := property.Value.Nullable
property.Value = openapi3.NewStringSchema()
property.Value.Nullable = nullable
property.Value.Description = field.Tag.Get("dc")
if !response {
property.Value.Extensions = map[string]any{"x-gin-binding": binding}
}
continue
}
if !response {
applyContractRules(property.Value, binding)
setContractDefault(property.Value, field.Tag)
}
}
return nil
}
}
// nullableContractRef 保留循环引用处的指针/集合可空语义,不把可空标志污染到共享组件。
// 入参:t 为原字段类型,ref 为生成引用;返回允许必要 null 值的引用。
func nullableContractRef(t reflect.Type, ref *openapi3.SchemaRef) *openapi3.SchemaRef {
if t.Kind() == reflect.Ptr {
if strings.HasPrefix(ref.Ref, "#/components/schemas/") {
null := openapi3.NewObjectSchema().WithNullable()
null.Enum = []any{nil}
return &openapi3.SchemaRef{Value: &openapi3.Schema{AnyOf: openapi3.SchemaRefs{ref, null.NewRef()}}}
}
t = t.Elem()
}
if ref.Value == nil {
return ref
}
if (t.Kind() == reflect.Slice || t.Kind() == reflect.Array) && ref.Value.Items != nil {
ref.Value.Items = nullableContractRef(t.Elem(), ref.Value.Items)
}
if t.Kind() == reflect.Map && ref.Value.AdditionalProperties.Schema != nil {
ref.Value.AdditionalProperties.Schema = nullableContractRef(t.Elem(), ref.Value.AdditionalProperties.Schema)
}
return ref
}
// responseFieldRequired 只标记不会被 omitempty/omitzero 或匿名指针父级省略的字段。
// 入参:root 为所属结构,field 为可见字段;返回是否保证存在对应 JSON 属性。
func responseFieldRequired(root reflect.Type, field reflect.StructField) bool {
tag := "," + field.Tag.Get("json") + ","
if strings.Contains(tag, ",omitempty,") || strings.Contains(tag, ",omitzero,") {
return false
}
for _, index := range field.Index[:len(field.Index)-1] {
root = root.Field(index).Type
if root.Kind() == reflect.Ptr {
return false
}
}
return true
}
// contractFieldName 返回指定绑定方式的静态字段名;入参为字段和 tag,- 表示隐藏。
func contractFieldName(field reflect.StructField, tag string) string {
name := strings.SplitN(field.Tag.Get(tag), ",", 2)[0]
if name == "" {
return field.Name
}
return name
}
// requiredContractField 仅将无默认值的无条件 required 映射为存在性约束。
// 入参:field 为字段声明;返回是否具有可直接表达的必填规则,零值检查仍由 binding 负责。
func requiredContractField(field reflect.StructField) bool {
if _, hasDefault := field.Tag.Lookup("default"); hasDefault {
return false
}
binding := field.Tag.Get("binding")
if strings.Contains(binding, "|") || strings.Contains(","+binding+",", ",omitempty,") || strings.Contains(","+binding+",", ",omitnil,") {
return false
}
for _, rule := range strings.Split(field.Tag.Get("binding"), ",") {
if rule == "required" {
return true
}
}
return false
}
// applyContractRules 将可等价表达的单字段规则映射为标准关键字,其余保留原始扩展。
// 入参:schema 为字段 Schema,binding 为声明;不修改 DTO,不注册运行时规则。
func applyContractRules(schema *openapi3.Schema, binding string) {
if binding == "" || binding == "-" {
return
}
if schema.Extensions == nil {
schema.Extensions = map[string]any{}
}
schema.Extensions["x-gin-binding"] = binding
if schema.Format == "byte" || schema.Format == "binary" {
return
}
// OR 和 omitempty 具有分支语义,不能静默转换成多个 AND 约束。
if strings.Contains(binding, "|") || strings.Contains(","+binding+",", ",omitempty,") || strings.Contains(","+binding+",", ",omitnil,") {
return
}
rules := strings.Split(binding, ",")
for index, rule := range rules {
if rule == "dive" {
if schema.Items != nil && schema.Items.Value != nil {
applyContractRules(schema.Items.Value, strings.Join(rules[index+1:], ","))
}
// Map 的 keys/endkeys 不能当作值约束;完整规则已在扩展中保留。
return
}
key, value, _ := strings.Cut(rule, "=")
switch key {
case "email":
if schema.Type.Is("string") {
schema.Format = "email"
}
case "uuid", "uuid3", "uuid4", "uuid5":
if schema.Type.Is("string") {
schema.Format = "uuid"
}
case "oneof":
values := []any{}
for _, token := range contractEnumTokens.FindAllString(value, -1) {
token = strings.Trim(token, "'")
var (
entry any = token
err error
)
if schema.Type.Is("integer") {
if strings.HasPrefix(token, "-") {
entry, err = strconv.ParseInt(token, 10, 64)
} else {
entry, err = strconv.ParseUint(token, 10, 64)
}
} else if schema.Type.Is("number") {
entry, err = strconv.ParseFloat(token, 64)
}
if err != nil {
values = nil
break
}
values = append(values, entry)
}
schema.Enum = values
case "min", "max", "len", "gte", "lte", "gt", "lt":
applyContractBound(schema, key, value)
}
}
}
// applyContractBound 按值类型区分数值、长度、集合及 Map 大小。
// 入参:schema 为字段结构,rule/value 为服务端规则;无法静态映射时仅保留 binding 扩展。
func applyContractBound(schema *openapi3.Schema, rule string, value string) {
if schema.Type.Is("integer") || schema.Type.Is("number") {
number, err := strconv.ParseFloat(value, 64)
if err != nil {
return
}
switch rule {
case "min", "gte":
schema.WithMin(number)
case "max", "lte":
schema.WithMax(number)
case "len":
schema.WithMin(number).WithMax(number)
case "gt":
schema.WithMin(number).WithExclusiveMin(true)
case "lt":
schema.WithMax(number).WithExclusiveMax(true)
}
return
}
length, err := strconv.ParseUint(value, 10, 64)
if err != nil {
return
}
minimum, maximum := rule == "min" || rule == "gte" || rule == "len", rule == "max" || rule == "lte" || rule == "len"
if rule == "gt" && length < ^uint64(0) {
minimum = true
length++
}
if rule == "lt" && length > 0 {
maximum = true
length--
}
switch {
case schema.Type.Is("string"):
if minimum {
schema.MinLength = length
}
if maximum {
schema.MaxLength = &length
}
case schema.Type.Is("array"):
if minimum {
schema.MinItems = length
}
if maximum {
schema.MaxItems = &length
}
case schema.Type.Is("object"):
if minimum {
schema.MinProps = length
}
if maximum {
schema.MaxProps = &length
}
}
}
// setContractDefault 只记录可安全按 JSON 标量表示的静态 default 声明。
// 入参:schema 为当前字段,tag 为声明;复杂类型默认值由应用补充,不执行反射赋值。
func setContractDefault(schema *openapi3.Schema, tag reflect.StructTag) {
value, exists := tag.Lookup("default")
if !exists {
return
}
if schema.Type.Is("string") {
schema.Default = value
return
}
if schema.Type.Is("integer") || schema.Type.Is("number") || schema.Type.Is("boolean") {
var (
decoded any
)
if json.Unmarshal([]byte(value), &decoded) == nil {
schema.Default = decoded
}
}
}
+321
View File
@@ -0,0 +1,321 @@
package http
import (
"context"
"encoding/json"
"errors"
"mime/multipart"
"net/http/httptest"
"strings"
"testing"
"github.com/getkin/kin-openapi/openapi3"
"github.com/gin-gonic/gin"
)
type contractInput struct {
ID int64 `json:"-" uri:"id" binding:"required,min=1"`
Email string `json:"email" form:"email" binding:"required,email" dc:"联系邮箱"`
State string `json:"state" form:"state" binding:"oneof='in progress' done"`
Names []string `json:"names" form:"names" binding:"min=1,max=3,dive,min=2"`
OwnerID int64 `json:"owner_id" form:"owner_id" binding:"required"`
}
type contractForm struct {
Meta `path:"/items/:id" method:"POST" summary:"更新条目" tag:"items" security:"bearer"`
contractInput
}
type contractNode struct {
Name string `json:"name" binding:"min=99"`
Next *contractNode `json:"next,omitempty"`
}
type contractController struct{ calls int }
func (c *contractController) Save(_ *gin.Context, form *contractForm) (*contractNode, error) {
c.calls++
return &contractNode{Name: form.Email}, nil
}
func TestOpenAPICoversMergedRequestResponseAndSecurity(t *testing.T) {
server, err := NewServer(Config{SuccessCode: 10}, Options{TrustedFields: map[string]TrustedField{"OwnerID": func(*gin.Context) (any, error) { return int64(1), nil }}})
if err != nil {
t.Fatal(err)
}
controller := &contractController{}
if err = server.Group("/api", nil, controller); err != nil {
t.Fatal(err)
}
schemes := openapi3.SecuritySchemes{"bearer": &openapi3.SecuritySchemeRef{Value: &openapi3.SecurityScheme{Type: "http", Scheme: "bearer", BearerFormat: "JWT"}}}
options := OpenAPIOptions{Title: "Example", Version: "1.0", SecuritySchemes: schemes}
doc, err := server.OpenAPI(options)
if err != nil {
t.Fatal(err, errors.Unwrap(err))
}
if controller.calls != 0 {
t.Fatal("generation executed controller")
}
operation := doc.Paths.Value("/api/items/{id}").Post
if operation.Summary != "更新条目" || operation.Tags[0] != "items" {
t.Fatal("metadata lost")
}
if operation.Security == nil || len(*operation.Security) != 1 {
t.Fatal("security declaration missing")
}
if _, ok := (*operation.Security)[0]["bearer"]; !ok {
t.Fatal("bearer requirement lost")
}
for _, parameter := range operation.Parameters {
if parameter.Value.Name == "owner_id" {
t.Fatal("trusted identity exposed as client input")
}
if parameter.Value.In == "path" && (!parameter.Value.Required || !parameter.Value.Schema.Value.Type.Is("integer") || *parameter.Value.Schema.Value.Min != 1) {
t.Fatal("path schema lost")
}
if parameter.Value.In == "query" && parameter.Value.Required {
t.Fatal("query cannot be independently required when body can supply it")
}
}
body := operation.RequestBody.Value.Content["application/json"].Schema.Value
if body.Properties["Meta"] != nil || body.Properties["owner_id"] != nil {
t.Fatal("framework/trusted fields leaked into body")
}
if len(body.Required) != 0 || body.Extensions["x-gin-required-after-merge"] == nil {
t.Fatal("merged-source presence was misrepresented")
}
if body.Properties["email"].Value.Format != "email" || body.Properties["email"].Value.Description != "联系邮箱" {
t.Fatal("field contract missing")
}
if body.Properties["state"].Value.Enum[0] != "in progress" {
t.Fatal("quoted enum split incorrectly")
}
array := body.Properties["names"].Value
if array.MinItems != 1 || *array.MaxItems != 3 || array.Items.Value.MinLength != 2 || array.Items.Value.MaxLength != nil {
t.Fatal("collection constraints applied to wrong level")
}
if err = doc.Validate(context.Background()); err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
request := httptest.NewRequest("POST", "/api/items/1", strings.NewReader(`{"email":"a@example.test","state":"done","names":["ok"]}`))
request.Header.Set("Content-Type", "application/json")
server.Handler().ServeHTTP(recorder, request)
if recorder.Code != 200 {
t.Fatalf("unexpected actual response %d: %s", recorder.Code, recorder.Body.String())
}
var (
actual any
)
if err = json.Unmarshal(recorder.Body.Bytes(), &actual); err != nil {
t.Fatal(err)
}
response := operation.Responses.Status(200).Value.Content["application/json"].Schema.Value
if response.Properties["data"].Value.Properties["name"].Value.MinLength != 0 {
t.Fatal("input rules incorrectly constrain unvalidated output")
}
if err = response.VisitJSON(actual); err != nil {
t.Fatalf("generated response disagrees with actual wire JSON: %v", err)
}
if response.Properties["data"].Value.Properties["next"].Ref == "" && response.Properties["data"].Value.Properties["next"].Value == nil {
t.Fatal("recursive response lost")
}
// 返回的文档和选项均不共享到 Server;冻结后也能再次生成。
doc.Components.SecuritySchemes["bearer"].Value.Scheme = "basic"
delete(body.Properties, "email")
next, err := server.OpenAPI(options)
if err != nil {
t.Fatal(err)
}
if schemes["bearer"].Value.Scheme != "bearer" || next.Paths.Value("/api/items/{id}").Post.RequestBody.Value.Content["application/json"].Schema.Value.Properties["email"] == nil {
t.Fatal("document mutation escaped snapshot")
}
}
type contractQueryForm struct {
Meta `path:"/search" method:"GET" security:"-"`
Term string `json:"term" form:"q" binding:"required,min=2"`
Page int `json:"page" form:"page" binding:"required,min=1" default:"1"`
Maybe string `json:"maybe" form:"maybe" binding:"omitempty,min=3"`
Bytes []byte `json:"bytes" form:"bytes" binding:"min=1"`
Filter struct {
Active bool `json:"active"`
} `json:"filter" form:"filter"`
}
type contractUploadForm struct {
Meta `path:"/files" method:"POST"`
File *multipart.FileHeader `json:"-" form:"file" binding:"required"`
}
type contractOtherController struct{}
func (*contractOtherController) Search(*gin.Context, *contractQueryForm) (map[string]any, error) {
return nil, nil
}
func (*contractOtherController) Upload(*gin.Context, *contractUploadForm) (any, error) {
return nil, nil
}
func TestOpenAPIQueryFilesNativeOverridesAndNoImplicitPublication(t *testing.T) {
server, _ := NewServer(Config{}, Options{})
if err := server.Group("", nil, &contractOtherController{}); err != nil {
t.Fatal(err)
}
if err := server.Handle("GET", "/stream/*tail", func(*gin.Context) {}); err != nil {
t.Fatal(err)
}
opts := OpenAPIOptions{Title: "Contract", Version: "v1", SecuritySchemes: openapi3.SecuritySchemes{"key": &openapi3.SecuritySchemeRef{Value: &openapi3.SecurityScheme{Type: "apiKey", In: "header", Name: "X-API-Key"}}}, Security: openapi3.SecurityRequirements{{"key": []string{}}}, Customize: func(meta Metadata, op *openapi3.Operation) error {
if meta.Path == "/stream/*tail" {
op.Responses = openapi3.NewResponses(openapi3.WithName("200", openapi3.NewResponse().WithDescription("SSE stream").WithContent(openapi3.Content{"text/event-stream": &openapi3.MediaType{Schema: openapi3.NewStringSchema().NewRef()}})))
}
return nil
}}
doc, err := server.OpenAPI(opts)
if err != nil {
t.Fatal(err)
}
search := doc.Paths.Value("/search").Get
if search.RequestBody != nil || search.Security == nil || len(*search.Security) != 0 {
t.Fatal("GET body or public security override incorrect")
}
for _, ref := range search.Parameters {
parameter := ref.Value
switch parameter.Name {
case "q":
if !parameter.Required || parameter.Schema.Value.MinLength != 2 {
t.Fatal("required query constraint missing")
}
case "page":
if parameter.Required || parameter.Schema.Value.Default != float64(1) {
t.Fatal("default incorrectly requires query input")
}
case "maybe":
if parameter.Schema.Value.MinLength != 0 || parameter.Schema.Value.Extensions["x-gin-binding"] == nil {
t.Fatal("conditional rule falsely strengthened")
}
case "filter":
if parameter.Schema != nil || parameter.Content["application/json"] == nil {
t.Fatal("structured query JSON representation lost")
}
case "bytes":
if !parameter.Schema.Value.Type.Is("array") || parameter.Schema.Value.MinItems != 1 || !parameter.Schema.Value.Items.Value.Type.Is("integer") {
t.Fatal("URL byte slice incorrectly described as base64 JSON string")
}
}
}
file := doc.Paths.Value("/files").Post.RequestBody.Value.Content["multipart/form-data"].Schema.Value.Properties["file"].Value
if file.Format != "binary" {
t.Fatal("multipart upload described as internal FileHeader")
}
stream := doc.Paths.Value("/stream/{tail}").Get
if stream.Extensions["x-gin-native"] != true || stream.Parameters[0].Value.Extensions["x-gin-catch-all"] != true || stream.Responses.Status(200).Value.Content["text/event-stream"] == nil {
t.Fatal("native contract override lost")
}
if err = server.Handle("GET", "/after-generation", func(*gin.Context) {}); err != nil {
t.Fatal("document generation froze registration", err)
}
recorder := httptest.NewRecorder()
server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", "/openapi.json", nil))
if recorder.Code != 404 {
t.Fatal("documentation was implicitly published")
}
}
func TestOpenAPIRejectsInvalidOrIncompleteDeclarations(t *testing.T) {
server, _ := NewServer(Config{}, Options{})
if _, err := server.OpenAPI(OpenAPIOptions{}); err == nil {
t.Fatal("missing info accepted")
}
if err := server.Group("", nil, &contractController{}); err != nil {
t.Fatal(err)
}
options := OpenAPIOptions{Title: "Contract", Version: "v1"}
if doc, err := server.OpenAPI(options); err == nil || doc != nil {
t.Fatal("undefined bearer scheme accepted")
}
options.Customize = func(_ Metadata, op *openapi3.Operation) error {
requirements := openapi3.SecurityRequirements{}
op.Security = &requirements
return nil
}
if _, err := server.OpenAPI(options); err != nil {
t.Fatal("explicit native security override rejected", err, errors.Unwrap(err))
}
sentinel := errors.New("contract customization failed")
options.Customize = func(Metadata, *openapi3.Operation) error { return sentinel }
if _, err := server.OpenAPI(options); !errors.Is(err, sentinel) {
t.Fatal("customizer cause lost")
}
options.Customize = func(_ Metadata, op *openapi3.Operation) error { op.Responses = openapi3.NewResponses(); return nil }
if doc, err := server.OpenAPI(options); err == nil || doc != nil {
t.Fatal("invalid final document accepted")
}
native, _ := NewServer(Config{}, Options{})
if err := native.Handle("GET", "/raw", func(*gin.Context) {}); err != nil {
t.Fatal(err)
}
doc, err := native.OpenAPI(OpenAPIOptions{Title: "Native", Version: "1"})
if err != nil {
t.Fatal(err)
}
if len(doc.Paths.Value("/raw").Get.Responses.Default().Value.Content) != 0 {
t.Fatal("native response schema invented")
}
}
type recursiveValue struct {
Age *int `json:"age,string"`
Object struct {
Enabled bool `json:"enabled"`
} `json:"object"`
Next *recursiveValue `json:"next"`
Children []*recursiveValue `json:"children"`
Values map[string]*recursiveValue `json:"values"`
}
type recursiveForm struct {
Meta `path:"/recursive" method:"GET"`
}
type recursiveController struct{}
func (*recursiveController) Get(*gin.Context, *recursiveForm) (recursiveValue, error) {
return recursiveValue{Children: []*recursiveValue{nil, {}}, Values: map[string]*recursiveValue{"none": nil}}, nil
}
func TestOpenAPIRecursiveValueKeepsNullableFieldsAndCollectionItems(t *testing.T) {
server, _ := NewServer(Config{}, Options{})
if err := server.Group("", nil, &recursiveController{}); err != nil {
t.Fatal(err)
}
doc, err := server.OpenAPI(OpenAPIOptions{Title: "Recursive", Version: "1"})
if err != nil {
t.Fatal(err, errors.Unwrap(err))
}
recorder := httptest.NewRecorder()
server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", "/recursive", nil))
var (
actual any
)
if err = json.Unmarshal(recorder.Body.Bytes(), &actual); err != nil {
t.Fatal(err)
}
schema := doc.Paths.Value("/recursive").Get.Responses.Status(200).Value.Content["application/json"].Schema.Value
if err = schema.VisitJSON(actual); err != nil {
t.Fatalf("recursive nulls disagree with wire JSON: %v", err)
}
}
type contractScalarRef string
type unsupportedReferenceOutput struct {
Reference contractScalarRef `json:"reference"`
}
type unsupportedReferenceController struct{}
func (*unsupportedReferenceController) Search(*gin.Context, *contractQueryForm) (unsupportedReferenceOutput, error) {
return unsupportedReferenceOutput{}, nil
}
func TestOpenAPIUnsupportedReferenceAliasReturnsError(t *testing.T) {
server, _ := NewServer(Config{}, Options{})
if err := server.Group("", nil, &unsupportedReferenceController{}); err != nil {
t.Fatal(err)
}
if doc, err := server.OpenAPI(OpenAPIOptions{Title: "Reference", Version: "1"}); err == nil || doc != nil {
t.Fatal("unsupported scalar Ref alias did not return an error")
}
}
+10
View File
@@ -47,6 +47,16 @@ const (
codeHealthConfig = 900429
codeReadinessCheck = 900430
codeRequestCancelled = 900431
codeOpenAPIOptions = 900432
codeOpenAPISchema = 900433
codeOpenAPIPath = 900434
codeOpenAPICustomize = 900435
codeOpenAPIValidate = 900436
codeOpenAPICopy = 900437
codeOpenAPISecurity = 900438
codeOpenAPIMethod = 900439
codeOpenAPIDuplicate = 900440
codeOpenAPIResponse = 900441
)
// PublicError 是业务显式允许公开的错误,不包含原始原因文本。
+5 -2
View File
@@ -20,7 +20,7 @@ import (
// Meta 通过 Form 内嵌字段的 tag 声明路由,Input 不依赖本包。
type Meta struct{}
// Metadata 是路由注册完成后的只读快照,可供应用生成 OpenAPI 文档。
// Metadata 是路由注册完成后的轻量只读快照,完整契约通过 Server.OpenAPI 生成。
type Metadata struct {
Method string `json:"method" dc:"大写 HTTP 方法"`
Path string `json:"path" dc:"包含分组前缀的最终路径"`
@@ -31,6 +31,9 @@ type Metadata struct {
type route struct {
meta Metadata `dc:"不可变路由元数据"`
handlers []gin.HandlerFunc `dc:"启动时装配的路由处理链"`
input reflect.Type `dc:"普通 Controller 的 Form 类型,原生路由为空"`
output reflect.Type `dc:"普通 Controller 的公开结果类型,原生路由为空"`
security string `dc:"Meta 声明的文档安全要求,不执行认证"`
}
// TrustedField 从可信认证上下文读取一个公共字段,不读取客户端原始输入。
@@ -97,7 +100,7 @@ func (s *Server) Group(prefix string, middleware []gin.HandlerFunc, controllers
verb = strings.ToUpper(strings.TrimSpace(verb))
handlers := append([]gin.HandlerFunc(nil), middleware...)
handlers = append(handlers, handler)
planned = append(planned, route{meta: Metadata{Method: verb, Path: path.Join("/", prefix, meta.Tag.Get("path")), Summary: meta.Tag.Get("summary"), Tag: meta.Tag.Get("tag")}, handlers: handlers})
planned = append(planned, route{meta: Metadata{Method: verb, Path: path.Join("/", prefix, meta.Tag.Get("path")), Summary: meta.Tag.Get("summary"), Tag: meta.Tag.Get("tag")}, handlers: handlers, input: formType, output: signature.Out(0), security: meta.Tag.Get("security")})
}
}
}
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.