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 }