示例#1
0
func (sg *schemaGenContext) makeNewStruct(name string, schema spec.Schema) *schemaGenContext {
	sp := sg.TypeResolver.Doc.Spec()
	name = swag.ToGoName(name)
	if sg.TypeResolver.ModelName != sg.Name {
		name = swag.ToGoName(sg.TypeResolver.ModelName + " " + name)
	}
	if sp.Definitions == nil {
		sp.Definitions = make(spec.Definitions)
	}
	sp.Definitions[name] = schema
	pg := schemaGenContext{
		Path:           "",
		Name:           name,
		Receiver:       "m",
		IndexVar:       "i",
		ValueExpr:      "m",
		Schema:         schema,
		Required:       false,
		Named:          true,
		ExtraSchemas:   make(map[string]GenSchema),
		Discrimination: sg.Discrimination,
	}
	if schema.Ref.String() == "" {
		pg.TypeResolver = &typeResolver{
			Doc:           sg.TypeResolver.Doc,
			ModelName:     sg.TypeResolver.ModelName,
			ModelsPackage: "",
		}
	}
	pg.GenSchema.IsVirtual = true

	sg.ExtraSchemas[name] = pg.GenSchema
	return &pg
}
示例#2
0
func (sg *schemaGenContext) makeNewStruct(name string, schema spec.Schema) *schemaGenContext {
	//fmt.Println("making new struct", name, sg.Container)
	sp := sg.TypeResolver.Doc.Spec()
	name = swag.ToGoName(name)
	if sg.TypeResolver.ModelName != sg.Name {
		name = swag.ToGoName(sg.TypeResolver.ModelName + " " + name)
	}
	if sp.Definitions == nil {
		sp.Definitions = make(spec.Definitions)
	}
	sp.Definitions[name] = schema
	pg := schemaGenContext{
		Path:           "",
		Name:           name,
		Receiver:       sg.Receiver,
		IndexVar:       "i",
		ValueExpr:      sg.Receiver,
		Schema:         schema,
		Required:       false,
		Named:          true,
		ExtraSchemas:   make(map[string]GenSchema),
		Discrimination: sg.Discrimination,
		Container:      sg.Container,
	}
	if schema.Ref.String() == "" {
		resolver := newTypeResolver(sg.TypeResolver.ModelsPackage, sg.TypeResolver.Doc)
		resolver.ModelName = sg.TypeResolver.ModelName
		pg.TypeResolver = resolver
	}
	pg.GenSchema.IsVirtual = true

	sg.ExtraSchemas[name] = pg.GenSchema
	return &pg
}
示例#3
0
func pascalize(arg string) string {
	if len(arg) == 0 || arg[0] > '9' {
		return swag.ToGoName(arg)
	}

	return swag.ToGoName("Nr " + arg)
}
示例#4
0
func (a *appGenerator) generateMain(app *GenApp) error {
	buf := bytes.NewBuffer(nil)
	if err := mainTemplate.Execute(buf, app); err != nil {
		return err
	}
	log.Println("rendered main template:", "server."+swag.ToGoName(app.Name))
	return writeToFile(filepath.Join(a.Target, "cmd", swag.ToCommandName(swag.ToGoName(app.Name)+"Server")), "main", buf.Bytes())
}
示例#5
0
func (a *appGenerator) generateAPIBuilder(app *GenApp) error {
	buf := bytes.NewBuffer(nil)
	if err := builderTemplate.Execute(buf, app); err != nil {
		return err
	}
	log.Println("rendered builder template:", app.Package+"."+swag.ToGoName(app.Name))
	return writeToFile(filepath.Join(a.Target, a.ServerPackage, app.Package), swag.ToGoName(app.Name)+"Api", buf.Bytes())
}
示例#6
0
func makeCodegenModel(name, pkg string, schema spec.Schema, specDoc *spec.Document) *genModel {
	receiver := "m"
	props := make(map[string]genModelProperty)
	for pn, p := range schema.Properties {
		var required bool
		for _, v := range schema.Required {
			if v == pn {
				required = true
				break
			}
		}
		props[swag.ToJSONName(pn)] = makeGenModelProperty(
			"\""+pn+"\"",
			swag.ToJSONName(pn),
			swag.ToGoName(pn),
			receiver,
			"i",
			receiver+"."+swag.ToGoName(pn),
			p,
			required)
	}
	for _, p := range schema.AllOf {
		if p.Ref.GetURL() != nil {
			tn := filepath.Base(p.Ref.GetURL().Fragment)
			p = specDoc.Spec().Definitions[tn]
		}
		mod := makeCodegenModel(name, pkg, p, specDoc)
		if mod != nil {
			for _, prop := range mod.Properties {
				props[prop.ParamName] = prop
			}
		}
	}

	var properties []genModelProperty
	var hasValidations bool
	for _, v := range props {
		if v.HasValidations {
			hasValidations = v.HasValidations
		}
		properties = append(properties, v)
	}

	sort.Sort(genModelPropertySlice(properties))

	return &genModel{
		Package:        filepath.Base(pkg),
		ClassName:      swag.ToGoName(name),
		Name:           swag.ToJSONName(name),
		ReceiverName:   receiver,
		Properties:     properties,
		Description:    schema.Description,
		DocString:      modelDocString(swag.ToGoName(name), schema.Description),
		HumanClassName: swag.ToHumanNameLower(swag.ToGoName(name)),
		DefaultImports: []string{"github.com/go-swagger/go-swagger/strfmt"},
		HasValidations: hasValidations,
	}
}
示例#7
0
func (t *typeResolver) goTypeName(nm string) string {
	if t.ModelsPackage == "" {
		return swag.ToGoName(nm)
	}
	if _, ok := t.KnownDefs[nm]; ok {
		return strings.Join([]string{t.ModelsPackage, swag.ToGoName(nm)}, ".")
	}
	return swag.ToGoName(nm)
}
示例#8
0
func (a *appGenerator) generateEmbeddedSwaggerJSON(app *GenApp) error {
	buf := bytes.NewBuffer(nil)
	appc := *app
	appc.Package = "main"
	if err := embeddedSpecTemplate.Execute(buf, &appc); err != nil {
		return err
	}
	log.Println("rendered embedded Swagger JSON template:", "server."+swag.ToGoName(app.Name))
	return writeToFile(filepath.Join(a.Target, "cmd", swag.ToCommandName(swag.ToGoName(app.Name)+"Server")), "embedded_spec", buf.Bytes())
}
示例#9
0
func makeCodegenParameter(receiver, modelsPkg string, param spec.Parameter) genParameter {
	var ctx sharedParam
	var child *genParameterItem

	if param.In == "body" {
		ctx = makeGenValidations(modelValidations(
			"\""+swag.ToJSONName(param.Name)+"\"",
			swag.ToJSONName(param.Name),
			swag.ToGoName(param.Name),
			"i",
			receiver+"."+swag.ToGoName(param.Name),
			modelsPkg,
			param.Required,
			*param.Schema))

	} else {
		ctx = makeGenValidations(paramValidations(receiver, param))
		thisItem := genParameterItem{}
		thisItem.sharedParam = ctx
		thisItem.ValueExpression = ctx.IndexVar + "c"
		thisItem.CollectionFormat = param.CollectionFormat
		thisItem.Converter = stringConverters[ctx.Type]
		thisItem.Location = param.In

		if param.Items != nil {
			it := makeCodegenParamItem(
				"fmt.Sprintf(\"%s.%v\", "+ctx.Path+", "+ctx.IndexVar+")",
				ctx.ParamName,
				ctx.PropertyName,
				ctx.IndexVar+"i",
				ctx.IndexVar+"c["+ctx.IndexVar+"]",
				thisItem,
				*param.Items,
			)
			child = &it
		}

	}

	return genParameter{
		sharedParam:      ctx,
		Description:      param.Description,
		ReceiverName:     receiver,
		IsQueryParam:     param.In == "query",
		IsBodyParam:      param.In == "body",
		IsHeaderParam:    param.In == "header",
		IsPathParam:      param.In == "path",
		IsFormParam:      param.In == "formData",
		IsFileParam:      param.Type == "file",
		CollectionFormat: param.CollectionFormat,
		Child:            child,
		Location:         param.In,
		Converter:        stringConverters[ctx.Type],
	}
}
示例#10
0
文件: client.go 项目: jak-atx/vic
func (c *clientGenerator) generateEmbeddedSwaggerJSON(app *GenApp) error {
	buf := bytes.NewBuffer(nil)

	if err := embeddedSpecTemplate.Execute(buf, app); err != nil {
		return err
	}
	log.Println("rendered client embedded swagger JSON template:", c.ClientPackage+"."+swag.ToGoName(app.Name)+"Client")

	fp := filepath.Join(c.Target, c.ClientPackage)
	return writeToFile(fp, swag.ToGoName(app.Name)+"EmbeddedSpec", buf.Bytes())
}
示例#11
0
func (c *clientGenerator) generateFacade(app *GenApp) error {
	buf := bytes.NewBuffer(nil)

	if err := clientFacadeTemplate.Execute(buf, app); err != nil {
		return err
	}
	log.Println("rendered client facade template:", c.ClientPackage+"."+swag.ToGoName(app.Name)+"Client")

	fp := filepath.Join(c.ClientPackage, c.Target)
	return writeToFile(fp, swag.ToGoName(app.Name)+"Client", buf.Bytes())
}
示例#12
0
func (c *clientGenerator) generateGroupClient(opGroup GenOperationGroup) error {
	buf := bytes.NewBuffer(nil)

	if err := clientTemplate.Execute(buf, opGroup); err != nil {
		return err
	}
	log.Println("rendered operation group client template:", opGroup.Name+"."+swag.ToGoName(opGroup.Name)+"Client")

	fp := filepath.Join(c.ClientPackage, c.Target, opGroup.Name)
	return writeToFile(fp, swag.ToGoName(opGroup.Name)+"Client", buf.Bytes())
}
示例#13
0
func (a *appGenerator) generateMain(app *GenApp) error {
	pth := filepath.Join(a.Target, "cmd", swag.ToCommandName(swag.ToGoName(app.Name)+"Server"))
	if fileExists(pth, "main") && !a.GenOpts.IncludeMain {
		log.Println("skipped (already exists) main template:", app.Package+".Main")
		return nil
	}
	buf := bytes.NewBuffer(nil)
	if err := mainTemplate.Execute(buf, app); err != nil {
		return err
	}
	log.Println("rendered main template:", "server."+swag.ToGoName(app.Name))
	return writeToFile(pth, "main", buf.Bytes())
}
示例#14
0
func (c *clientGenerator) generateParameters(op *GenOperation) error {
	buf := bytes.NewBuffer(nil)

	if err := clientParamTemplate.Execute(buf, op); err != nil {
		return err
	}
	log.Println("rendered client parameters template:", op.Package+"."+swag.ToGoName(op.Name)+"Parameters")

	fp := filepath.Join(c.ClientPackage, c.Target)
	if len(op.Package) > 0 {
		fp = filepath.Join(fp, op.Package)
	}
	return writeToFile(fp, swag.ToGoName(op.Name)+"Parameters", buf.Bytes())
}
示例#15
0
func discriminatorInfo(doc *spec.Document) *discInfo {
	baseTypes := make(map[string]discor)
	for _, sch := range doc.AllDefinitions() {
		if sch.Schema.Discriminator != "" {
			tpe, _ := sch.Schema.Extensions.GetString("x-go-name")
			if tpe == "" {
				tpe = swag.ToGoName(sch.Name)
			}
			baseTypes[sch.Ref.String()] = discor{
				FieldName: sch.Schema.Discriminator,
				GoType:    tpe,
				JSONName:  sch.Name,
			}
		}
	}

	subTypes := make(map[string]discee)
	for _, sch := range doc.SchemasWithAllOf() {
		for _, ao := range sch.Schema.AllOf {
			if ao.Ref.String() != "" {
				if bt, ok := baseTypes[ao.Ref.String()]; ok {
					name, _ := sch.Schema.Extensions.GetString("x-class")
					if name == "" {
						name, _ = sch.Schema.Extensions.GetString("x-go-name")
					}
					if name == "" {
						name = swag.ToGoName(sch.Name)
					}
					tpe, _ := sch.Schema.Extensions.GetString("x-go-name")
					if tpe == "" {
						tpe = swag.ToGoName(sch.Name)
					}
					dce := discee{
						FieldName:  bt.FieldName,
						FieldValue: name,
						Ref:        sch.Ref,
						ParentRef:  ao.Ref,
						JSONName:   sch.Name,
						GoType:     tpe,
					}
					subTypes[sch.Ref.String()] = dce
					bt.Children = append(bt.Children, dce)
					baseTypes[ao.Ref.String()] = bt
				}
			}
		}
	}
	return &discInfo{Discriminators: baseTypes, Discriminated: subTypes}
}
示例#16
0
func (a *appGenerator) generateConfigureAPI(app *GenApp) error {
	pth := filepath.Join(a.Target, "cmd", swag.ToCommandName(swag.ToGoName(app.Name)+"Server"))
	nm := "Configure" + swag.ToGoName(app.Name)
	if fileExists(pth, nm) {
		log.Println("skipped (already exists) configure api template:", app.Package+".Configure"+swag.ToGoName(app.Name))
		return nil
	}

	buf := bytes.NewBuffer(nil)
	if err := configureAPITemplate.Execute(buf, app); err != nil {
		return err
	}
	log.Println("rendered configure api template:", app.Package+".Configure"+swag.ToGoName(app.Name))
	return writeToFileIfNotExist(pth, nm, buf.Bytes())
}
示例#17
0
func TestSchemaValidation_RequiredProps(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "RequiredProps"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			assert.Len(t, gm.Properties, 6)
			for _, p := range gm.Properties {
				if assert.True(t, p.Required) {
					buf := bytes.NewBuffer(nil)
					err := modelTemplate.Execute(buf, gm)
					if assert.NoError(t, err) {
						formatted, err := formatGoFile("required_props.go", buf.Bytes())
						if assert.NoError(t, err) {
							res := string(formatted)
							assertInCode(t, k+") Validate(formats", res)
							assertInCode(t, "validate"+swag.ToGoName(p.Name), res)
							assertInCode(t, "err := validate.Required", res)
							assertInCode(t, "errors.CompositeValidationError(res...)", res)
						}
					}
				}
			}
		}
	}
}
示例#18
0
func modelValidations(gs GenSchema) commonValidations {

	return commonValidations{
		propertyDescriptor: propertyDescriptor{
			PropertyName:      swag.ToGoName(gs.Name),
			ParamName:         gs.Name,
			ValueExpression:   gs.ValueExpression,
			IndexVar:          gs.IndexVar,
			Path:              gs.Path,
			IsContainer:       gs.IsArray,
			IsPrimitive:       gs.IsPrimitive,
			IsCustomFormatter: gs.IsCustomFormatter,
			IsMap:             gs.IsMap,
		},
		sharedValidations: sharedValidations{
			Required:         gs.Required,
			Maximum:          gs.Maximum,
			ExclusiveMaximum: gs.ExclusiveMaximum,
			Minimum:          gs.Minimum,
			ExclusiveMinimum: gs.ExclusiveMinimum,
			MaxLength:        gs.MaxLength,
			MinLength:        gs.MinLength,
			Pattern:          gs.Pattern,
			MaxItems:         gs.MaxItems,
			MinItems:         gs.MinItems,
			UniqueItems:      gs.UniqueItems,
			MultipleOf:       gs.MultipleOf,
			Enum:             gs.Enum,
		},
		Type:   gs.GoType,
		Format: gs.SwaggerFormat,
		//Default:          model.Default,
	}
}
示例#19
0
func (sg *schemaGenContext) NewAdditionalItems(schema *spec.Schema) *schemaGenContext {
	pg := sg.shallowClone()
	indexVar := pg.IndexVar
	pg.Name = sg.Name + " items"
	itemsLen := 0
	if sg.Schema.Items != nil {
		itemsLen = sg.Schema.Items.Len()
	}
	var mod string
	if itemsLen > 0 {
		mod = "+" + strconv.Itoa(itemsLen)
	}
	if pg.Path == "" {
		pg.Path = "strconv.Itoa(" + indexVar + mod + ")"
	} else {
		pg.Path = pg.Path + "+ \".\" + strconv.Itoa(" + indexVar + mod + ")"
	}
	pg.IndexVar = indexVar
	pg.ValueExpr = sg.ValueExpr + "." + swag.ToGoName(sg.Name) + "Items[" + indexVar + "]"
	pg.Schema = spec.Schema{}
	if schema != nil {
		pg.Schema = *schema
	}
	pg.Required = false
	return pg
}
示例#20
0
func (t *typeResolver) resolveSchemaRef(schema *spec.Schema) (returns bool, result resolvedType, err error) {
	if schema.Ref.String() != "" {
		returns = true
		ref, er := spec.ResolveRef(t.Doc.Spec(), &schema.Ref)
		if er != nil {
			err = er
			return
		}
		var nm = filepath.Base(schema.Ref.GetURL().Fragment)
		var tn string
		if gn, ok := ref.Extensions["x-go-name"]; ok {
			tn = gn.(string)
		} else {
			tn = swag.ToGoName(nm)
		}

		res, er := t.ResolveSchema(ref, false)
		if er != nil {
			err = er
			return
		}
		result = res
		result.GoType = tn
		result.HasDiscriminator = ref.Discriminator != ""
		result.IsNullable = t.isNullable(ref)
		if t.ModelsPackage != "" {
			result.GoType = t.ModelsPackage + "." + tn
		}
		return

	}
	return
}
示例#21
0
func (sg *schemaGenContext) buildProperties() error {
	for k, v := range sg.Schema.Properties {
		// check if this requires de-anonymizing, if so lift this as a new struct and extra schema
		tpe, err := sg.TypeResolver.ResolveSchema(&v, true)
		if err != nil {
			return err
		}

		vv := v
		var hasValidations bool
		var needsValidations bool
		if tpe.IsComplexObject && tpe.IsAnonymous && len(v.Properties) > 0 {
			pg := sg.makeNewStruct(sg.Name+swag.ToGoName(k), v)
			if sg.Path != "" {
				pg.Path = sg.Path + "+ \".\"+" + fmt.Sprintf("%q", k)
			} else {
				pg.Path = fmt.Sprintf("%q", k)
			}
			if err := pg.makeGenSchema(); err != nil {
				return err
			}
			if v.Discriminator != "" {
				pg.GenSchema.IsBaseType = true
				pg.GenSchema.IsExported = true
				pg.GenSchema.HasBaseType = true
			}

			vv = *spec.RefProperty("#/definitions/" + pg.Name)
			hasValidations = pg.GenSchema.HasValidations
			needsValidations = pg.GenSchema.NeedsValidation
			sg.MergeResult(pg, false)
			sg.ExtraSchemas[pg.Name] = pg.GenSchema
		}

		emprop := sg.NewStructBranch(k, vv)
		if err := emprop.makeGenSchema(); err != nil {
			return err
		}
		if hasValidations || emprop.GenSchema.HasValidations {
			emprop.GenSchema.HasValidations = true
		}
		if needsValidations || emprop.GenSchema.NeedsValidation {
			emprop.GenSchema.NeedsValidation = true
		}
		if emprop.Schema.Ref.String() != "" {
			if _, ok := emprop.Discrimination.Discriminators[emprop.Schema.Ref.String()]; ok {
				emprop.GenSchema.IsBaseType = true
				emprop.GenSchema.IsNullable = false
				emprop.GenSchema.HasBaseType = true
			}
			if _, ok := emprop.Discrimination.Discriminated[emprop.Schema.Ref.String()]; ok {
				emprop.GenSchema.IsSubType = true
			}
		}
		sg.MergeResult(emprop, false)
		sg.GenSchema.Properties = append(sg.GenSchema.Properties, emprop.GenSchema)
	}
	sort.Sort(sg.GenSchema.Properties)
	return nil
}
示例#22
0
文件: support.go 项目: jak-atx/vic
func (a *appGenerator) Generate() error {

	app, err := a.makeCodegenApp()
	if err != nil {
		return err
	}

	if a.DumpData {
		bb, err := json.MarshalIndent(app, "", "  ")
		if err != nil {
			return err
		}
		fmt.Fprintln(os.Stdout, string(bb))
		return nil
	}

	if a.GenOpts.IncludeModel {
		log.Printf("rendering %d models", len(app.Models))
		for _, mod := range app.Models {
			mod.IncludeValidator = true // a.GenOpts.IncludeValidator
			gen := &definitionGenerator{
				Name:    mod.Name,
				SpecDoc: a.SpecDoc,
				Target:  filepath.Join(a.Target, a.ModelsPackage),
				Data:    &mod,
			}
			if err := gen.generateModel(); err != nil {
				return err
			}
		}
	}

	if a.GenOpts.IncludeHandler {
		for _, opg := range app.OperationGroups {
			for _, op := range opg.Operations {
				gen := &opGen{
					data:              &op,
					pkg:               opg.Name,
					cname:             swag.ToGoName(op.Name),
					IncludeHandler:    a.GenOpts.IncludeHandler,
					IncludeParameters: a.GenOpts.IncludeParameters,
					IncludeResponses:  a.GenOpts.IncludeResponses,
					Doc:               a.SpecDoc,
					Target:            filepath.Join(a.Target, a.ServerPackage),
					APIPackage:        a.APIPackage,
				}

				if err := gen.Generate(); err != nil {
					return err
				}
			}
		}
	}

	if a.GenOpts.IncludeSupport {
		return a.GenerateSupport(&app)
	}
	return nil
}
示例#23
0
func (b *codeGenOpBuilder) MakeResponse(receiver, name string, isSuccess bool, resolver *typeResolver, code int, resp spec.Response) (GenResponse, error) {

	res := GenResponse{
		Package:        b.APIPackage,
		ModelsPackage:  b.ModelsPackage,
		ReceiverName:   receiver,
		Name:           name,
		Description:    resp.Description,
		DefaultImports: nil,
		Imports:        nil,
		IsSuccess:      isSuccess,
		Code:           code,
	}

	for hName, header := range resp.Headers {
		res.Headers = append(res.Headers, b.MakeHeader(receiver, hName, header))
	}
	sort.Sort(res.Headers)

	if resp.Schema != nil {
		sc := schemaGenContext{
			Path:         fmt.Sprintf("%q", name),
			Name:         name + "Body",
			Receiver:     receiver,
			ValueExpr:    receiver,
			IndexVar:     "i",
			Schema:       *resp.Schema,
			Required:     true,
			TypeResolver: resolver,
			Named:        false,
			ExtraSchemas: make(map[string]GenSchema),
		}
		if err := sc.makeGenSchema(); err != nil {
			return GenResponse{}, err
		}

		for k, v := range sc.ExtraSchemas {
			b.ExtraSchemas[k] = v
		}

		schema := sc.GenSchema
		if schema.IsAnonymous {

			schema.Name = swag.ToGoName(sc.Name + " Body")
			nm := schema.Name
			if b.ExtraSchemas == nil {
				b.ExtraSchemas = make(map[string]GenSchema)
			}
			b.ExtraSchemas[schema.Name] = schema
			schema = GenSchema{}
			schema.IsAnonymous = false
			schema.GoType = nm
			schema.SwaggerType = nm
		}

		res.Schema = &schema
	}
	return res, nil
}
示例#24
0
func (sg *schemaGenContext) buildItems() error {
	presentsAsSingle := sg.Schema.Items != nil && sg.Schema.Items.Schema != nil
	if presentsAsSingle && sg.Schema.AdditionalItems != nil { // unsure if htis a valid of invalid schema
		return fmt.Errorf("single schema (%s) can't have additional items", sg.Name)
	}
	if presentsAsSingle {
		return sg.buildArray()
	}
	if sg.Schema.Items == nil {
		return nil
	}
	// This is a tuple, build a new model that represents this
	if sg.Named {
		sg.GenSchema.Name = sg.Name
		sg.GenSchema.GoType = swag.ToGoName(sg.Name)
		if sg.TypeResolver.ModelsPackage != "" {
			sg.GenSchema.GoType = sg.TypeResolver.ModelsPackage + "." + sg.GenSchema.GoType
		}
		for i, s := range sg.Schema.Items.Schemas {
			elProp := sg.NewTupleElement(&s, i)
			if err := elProp.makeGenSchema(); err != nil {
				return err
			}
			sg.MergeResult(elProp, false)
			elProp.GenSchema.Name = "p" + strconv.Itoa(i)
			sg.GenSchema.Properties = append(sg.GenSchema.Properties, elProp.GenSchema)
		}
		return nil
	}

	// for an anonoymous object, first build the new object
	// and then replace the current one with a $ref to the
	// new tuple object
	var sch spec.Schema
	sch.Typed("object", "")
	sch.Properties = make(map[string]spec.Schema)
	for i, v := range sg.Schema.Items.Schemas {
		sch.Required = append(sch.Required, "P"+strconv.Itoa(i))
		sch.Properties["P"+strconv.Itoa(i)] = v
	}
	sch.AdditionalItems = sg.Schema.AdditionalItems
	tup := sg.makeNewStruct(sg.GenSchema.Name+"Tuple"+strconv.Itoa(sg.Index), sch)
	if err := tup.makeGenSchema(); err != nil {
		return err
	}
	tup.GenSchema.IsTuple = true
	tup.GenSchema.IsComplexObject = false
	tup.GenSchema.Title = tup.GenSchema.Name + " a representation of an anonymous Tuple type"
	tup.GenSchema.Description = ""
	sg.ExtraSchemas[tup.Name] = tup.GenSchema

	sg.Schema = *spec.RefProperty("#/definitions/" + tup.Name)
	if err := sg.makeGenSchema(); err != nil {
		return err
	}
	sg.MergeResult(tup, false)
	return nil
}
示例#25
0
func appNameOrDefault(specDoc *spec.Document, name, defaultName string) string {
	if name == "" {
		if specDoc.Spec().Info != nil && specDoc.Spec().Info.Title != "" {
			name = specDoc.Spec().Info.Title
		} else {
			name = defaultName
		}
	}
	return strings.TrimSuffix(swag.ToGoName(name), "API")
}
示例#26
0
func ensureUniqueName(key, method, path string, operations map[string]opRef) string {
	nm := key
	if nm == "" {
		nm = swag.ToGoName(strings.ToLower(method) + " " + path)
	}
	_, found := operations[nm]
	if found {
		namesCounter++
		return fmt.Sprintf("%s%d", nm, namesCounter)
	}
	return nm
}
示例#27
0
func (o *opGen) generateResponses() error {
	buf := bytes.NewBuffer(nil)

	if err := responsesTemplate.Execute(buf, o.data); err != nil {
		return err
	}
	log.Println("rendered responses template:", o.pkg+"."+o.cname+"Responses")

	fp := filepath.Join(o.Target, o.pkg)
	if o.pkg != o.APIPackage {
		fp = filepath.Join(o.Target, o.APIPackage, o.pkg)
	}
	return writeToFile(fp, swag.ToGoName(o.data.Name)+"Responses", buf.Bytes())
}
示例#28
0
func (sg *schemaGenContext) makeNewStruct(name string, schema spec.Schema) *schemaGenContext {
	sp := sg.TypeResolver.Doc.Spec()
	name = swag.ToGoName(name)
	if sg.TypeResolver.ModelName != sg.Name {
		name = swag.ToGoName(sg.TypeResolver.ModelName + " " + name)
	}
	sp.Definitions[name] = schema
	pg := schemaGenContext{
		Path:         "",
		Name:         name,
		Receiver:     "m",
		IndexVar:     "i",
		ValueExpr:    "m",
		Schema:       schema,
		Required:     false,
		TypeResolver: sg.TypeResolver,
		Named:        true,
		ExtraSchemas: make(map[string]GenSchema),
	}
	pg.GenSchema.IsVirtual = true

	sg.ExtraSchemas[name] = pg.GenSchema
	return &pg
}
示例#29
0
func (sg *schemaGenContext) NewStructBranch(name string, schema spec.Schema) *schemaGenContext {
	pg := sg.shallowClone()
	if sg.Path == "" {
		pg.Path = fmt.Sprintf("%q", name)
	} else {
		pg.Path = pg.Path + "+\".\"+" + fmt.Sprintf("%q", name)
	}
	pg.Name = name
	pg.ValueExpr = pg.ValueExpr + "." + swag.ToGoName(name)
	pg.Schema = schema
	for _, fn := range sg.Schema.Required {
		if name == fn {
			pg.Required = true
			break
		}
	}
	return pg
}
示例#30
0
文件: types.go 项目: gbjk/go-swagger
func typeForSchema(schema *spec.Schema, modelsPkg string) string {
	if schema == nil {
		return "interface{}"
	}
	if schema.Ref.GetURL() != nil {
		tn := swag.ToGoName(filepath.Base(schema.Ref.GetURL().Fragment))
		if modelsPkg != "" {
			return modelsPkg + "." + tn
		}
		return tn
	}
	if schema.Format != "" {
		if tpe, ok := typeMapping[strings.Replace(schema.Format, "-", "", -1)]; ok {
			return tpe
		}
	}
	if schema.Type.Contains("array") {
		return "[]" + typeForSchemaOrArray(schema.Items, modelsPkg)
	}
	if schema.Type.Contains("file") {
		return typeMapping["file"]
	}
	if schema.Type.Contains("number") {
		return typeMapping["number"]
	}
	if schema.Type.Contains("integer") {
		return typeMapping["integer"]
	}
	if schema.Type.Contains("boolean") {
		return typeMapping["boolean"]
	}
	if schema.Type.Contains("string") {
		return "string"
	}
	if schema.AdditionalProperties != nil && schema.AdditionalProperties.Schema != nil {
		return "map[string]" + typeForSchema(schema.AdditionalProperties.Schema, modelsPkg)
	}
	if schema.Type.Contains("object") || schema.Type.Contains("") || len(schema.Type) == 0 {
		return "map[string]interface{}"
	}
	return "interface{}"
}