コード例 #1
0
ファイル: schema.go プロジェクト: Cl0udPhish/go-swagger
// Validate validates the data against the schema
func (s *SchemaValidator) Validate(data interface{}) *Result {
	if data == nil {
		v := s.validators[0].Validate(data)
		v.Merge(s.validators[6].Validate(data))
		return v
	}
	result := new(Result)

	tpe := reflect.TypeOf(data)
	kind := tpe.Kind()
	for kind == reflect.Ptr {
		tpe = tpe.Elem()
		kind = tpe.Kind()
	}
	d := data
	if kind == reflect.Struct {
		d = swag.ToDynamicJSON(data)
	}

	for _, v := range s.validators {
		if !v.Applies(s.Schema, kind) {
			continue
		}

		err := v.Validate(d)
		result.Merge(err)
		result.Inc()
	}
	result.Inc()
	return result
}
コード例 #2
0
ファイル: model.go プロジェクト: Cl0udPhish/go-swagger
func (m *definitionGenerator) Generate() error {

	mod, err := makeGenDefinition(m.Name, m.Target, m.Model, m.SpecDoc, m.IncludeValidator, m.IncludeStruct)
	if err != nil {
		return err
	}
	if m.DumpData {
		bb, _ := json.MarshalIndent(swag.ToDynamicJSON(mod), "", " ")
		fmt.Fprintln(os.Stdout, string(bb))
		return nil
	}

	mod.IncludeValidator = m.IncludeValidator
	mod.IncludeModel = m.IncludeStruct
	m.Data = mod
	if !m.IncludeStruct {
		m.Name += "_validator"
	}

	if m.IncludeModel {
		if err := m.generateModel(); err != nil {
			return fmt.Errorf("model: %s", err)
		}
	}
	log.Println("generated model", m.Name)

	return nil
}
コード例 #3
0
// Validate validates the data against the schema
func (s *SchemaValidator) Validate(data interface{}) *Result {
	if data == nil {
		v := s.validators[0].Validate(data)
		v.Merge(s.validators[6].Validate(data))
		return v
	}
	result := new(Result)

	tpe := reflect.TypeOf(data)
	kind := tpe.Kind()
	for kind == reflect.Ptr {
		tpe = tpe.Elem()
		kind = tpe.Kind()
	}
	d := data
	if kind == reflect.Struct {
		d = swag.ToDynamicJSON(data)
	}

	isnumber := s.Schema.Type.Contains("number") || s.Schema.Type.Contains("integer")
	if num, ok := data.(json.Number); ok && isnumber {
		if s.Schema.Type.Contains("integer") { // avoid lossy conversion
			in, erri := num.Int64()
			if erri != nil {
				result.AddErrors(erri)
				result.Inc()
				return result
			}
			d = in
		} else {
			nf, errf := num.Float64()
			if errf != nil {
				result.AddErrors(errf)
				result.Inc()
				return result
			}
			d = nf
		}

		tpe = reflect.TypeOf(d)
		kind = tpe.Kind()
	}

	for _, v := range s.validators {
		if !v.Applies(s.Schema, kind) {
			if Debug {
				log.Printf("%T does not apply for %v", v, kind)
			}
			continue
		}

		err := v.Validate(d)
		result.Merge(err)
		result.Inc()
	}
	result.Inc()
	return result
}
コード例 #4
0
ファイル: model.go プロジェクト: Cl0udPhish/go-swagger
func (m *definitionGenerator) generateModel() error {
	buf := bytes.NewBuffer(nil)

	if Debug {
		log.Printf("rendering model template: %s", m.Name)
		bb, _ := json.MarshalIndent(swag.ToDynamicJSON(m.Data), "", " ")
		fmt.Fprintln(os.Stdout, string(bb))
	}

	if err := modelTemplate.Execute(buf, m.Data); err != nil {
		return err
	}
	log.Println("rendered model template:", m.Name)

	return writeToFile(m.Target, m.Name, buf.Bytes())
}
コード例 #5
0
ファイル: spec.go プロジェクト: Cl0udPhish/go-swagger
// Execute this command
func (s *Spec) Execute(args []string) error {
	targetPath := "."
	if len(args) > 0 {
		targetPath = args[0]
	}
	realPath, err := filepath.Abs(targetPath)
	if err != nil {
		return err
	}
	var file *os.File
	switch s.Format {
	case "json":
		file, err = os.Create(filepath.Join(realPath, "swagger.json"))
		if err != nil {
			return err
		}
	case "yaml", "yml":
		file, err = os.Create(filepath.Join(realPath, "swagger.yml"))
		if err != nil {
			return err
		}
	default:
		return fmt.Errorf("invalid format: %s", s.Format)
	}
	defer file.Close()
	log.Println("creating specification document in", filepath.Join(targetPath, file.Name()))

	var doc spec.Swagger
	info := new(spec.Info)
	doc.Info = info

	doc.Swagger = "2.0"
	doc.Paths = new(spec.Paths)
	doc.Definitions = make(spec.Definitions)

	info.Title = s.Title
	if info.Title == "" {
		info.Title = swag.ToHumanNameTitle(filepath.Base(realPath))
	}
	info.Description = s.Description
	info.Version = s.Version
	info.TermsOfService = s.Terms
	if s.Contact.Name != "" || s.Contact.Email != "" || s.Contact.URL != "" {
		var contact spec.ContactInfo
		contact.Name = s.Contact.Name
		contact.Email = s.Contact.Email
		contact.URL = s.Contact.URL
		info.Contact = &contact
	}
	if s.License.Name != "" || s.License.URL != "" {
		var license spec.License
		license.Name = s.License.Name
		license.URL = s.License.URL
		info.License = &license
	}

	for _, cons := range s.Consumes {
		doc.Consumes = append(doc.Consumes, cons)
	}
	for _, prods := range s.Produces {
		doc.Produces = append(doc.Produces, prods)
	}
	for _, scheme := range s.Schemes {
		doc.Schemes = append(doc.Schemes, scheme)
	}

	if s.Format == "json" {
		enc := json.NewEncoder(file)
		if err := enc.Encode(doc); err != nil {
			return err
		}
		return nil
	}

	b, err := yaml.Marshal(swag.ToDynamicJSON(doc))
	if err != nil {
		return err
	}
	if _, err := file.Write(b); err != nil {
		return err
	}
	return nil
}
コード例 #6
0
ファイル: operation.go プロジェクト: Cl0udPhish/go-swagger
func (o *operationGenerator) Generate() error {
	// Build a list of codegen operations based on the tags,
	// the tag decides the actual package for an operation
	// the user specified package serves as root for generating the directory structure
	var operations GenOperations
	authed := len(o.SecurityRequirements) > 0

	var bldr codeGenOpBuilder
	bldr.Name = o.Name
	bldr.Method = o.Method
	bldr.Path = o.Path
	bldr.ModelsPackage = o.ModelsPackage
	bldr.Principal = o.Principal
	bldr.Target = o.Target
	bldr.Operation = o.Operation
	bldr.Authed = authed
	bldr.Doc = o.Doc
	bldr.Analyzed = o.Analyzed
	bldr.DefaultScheme = o.DefaultScheme
	bldr.DefaultProduces = o.DefaultProduces
	bldr.DefaultImports = []string{filepath.ToSlash(filepath.Join(baseImport(o.Base), o.ModelsPackage))}
	bldr.RootAPIPackage = o.APIPackage
	bldr.WithContext = o.WithContext
	bldr.DefaultConsumes = o.DefaultConsumes

	for _, tag := range o.Operation.Tags {
		if len(o.Tags) == 0 {
			bldr.APIPackage = mangleName(swag.ToFileName(tag), o.APIPackage)
			op, err := bldr.MakeOperation()
			if err != nil {
				return err
			}
			operations = append(operations, op)
			continue
		}
		for _, ft := range o.Tags {
			if ft == tag {
				bldr.APIPackage = mangleName(swag.ToFileName(tag), o.APIPackage)
				op, err := bldr.MakeOperation()
				if err != nil {
					return err
				}
				operations = append(operations, op)
				break
			}
		}
	}
	if len(operations) == 0 {
		bldr.APIPackage = o.APIPackage
		op, err := bldr.MakeOperation()
		if err != nil {
			return err
		}
		operations = append(operations, op)
	}
	sort.Sort(operations)

	for _, op := range operations {
		if o.DumpData {
			bb, _ := json.MarshalIndent(swag.ToDynamicJSON(op), "", " ")
			fmt.Fprintln(os.Stdout, string(bb))
			continue
		}
		og := new(opGen)
		og.IncludeHandler = o.IncludeHandler
		og.IncludeParameters = o.IncludeParameters
		og.IncludeResponses = o.IncludeResponses
		og.data = &op
		og.pkg = op.Package
		og.cname = swag.ToGoName(op.Name)
		og.Doc = o.Doc
		og.Analyzed = o.Analyzed
		og.Target = o.Target
		og.APIPackage = o.APIPackage
		og.WithContext = o.WithContext
		return og.Generate()
	}

	return nil
}
コード例 #7
0
ファイル: client.go プロジェクト: Cl0udPhish/go-swagger
func (c *clientGenerator) Generate() error {
	app, err := c.makeCodegenApp()
	if app.Name == "" {
		app.Name = "APIClient"
	}
	app.DefaultImports = []string{filepath.ToSlash(filepath.Join(baseImport(c.Target), c.ModelsPackage))}
	if err != nil {
		return err
	}

	if c.DumpData {
		bb, _ := json.MarshalIndent(swag.ToDynamicJSON(app), "", "  ")
		fmt.Fprintln(os.Stdout, string(bb))
		return nil
	}

	errChan := make(chan error, 100)
	wg := nsync.NewControlWaitGroup(20)

	if c.GenOpts.IncludeModel {
		for _, mod := range app.Models {
			if len(errChan) > 0 {
				wg.Wait()
				return <-errChan
			}
			modCopy := mod
			wg.Do(func() {
				modCopy.IncludeValidator = true // a.GenOpts.IncludeValidator
				gen := &definitionGenerator{
					Name:    modCopy.Name,
					SpecDoc: c.SpecDoc,
					Target:  filepath.Join(c.Target, c.ModelsPackage),
					Data:    &modCopy,
				}
				if err := gen.generateModel(); err != nil {
					errChan <- err
				}
			})
		}
	}

	wg.Wait()
	if c.GenOpts.IncludeHandler {
		sort.Sort(app.OperationGroups)
		for i := range app.OperationGroups {
			opGroup := app.OperationGroups[i]
			opGroup.DefaultImports = []string{filepath.ToSlash(filepath.Join(baseImport(c.Target), c.ModelsPackage))}
			opGroup.RootPackage = c.ClientPackage
			app.OperationGroups[i] = opGroup
			sort.Sort(opGroup.Operations)
			for _, op := range opGroup.Operations {
				if len(errChan) > 0 {
					wg.Wait()
					return <-errChan
				}
				opCopy := op
				if opCopy.Package == "" {
					opCopy.Package = c.Package
				}
				wg.Do(func() {
					if err := c.generateParameters(&opCopy); err != nil {
						errChan <- err
					}
				})
				wg.Do(func() {
					if err := c.generateResponses(&opCopy); err != nil {
						errChan <- err
					}
				})
			}
			app.DefaultImports = append(app.DefaultImports, filepath.ToSlash(filepath.Join(baseImport(c.Target), c.ClientPackage, opGroup.Name)))
			if err := c.generateGroupClient(opGroup); err != nil {
				return err
			}
		}
		wg.Wait()
	}

	if c.GenOpts.IncludeSupport {
		wg.Do(func() {
			if err := c.generateFacade(&app); err != nil {
				errChan <- err
			}
		})
	}

	wg.Wait()

	if len(errChan) > 0 {
		return <-errChan
	}

	return nil
}