示例#1
0
文件: swagger.go 项目: is00hcw/goa
// New creates a Swagger spec from an API definition.
func New(api *design.APIDefinition) (*Swagger, error) {
	if api == nil {
		return nil, nil
	}
	tags, err := tagsFromDefinition(api.Metadata)
	if err != nil {
		return nil, err
	}
	params, err := paramsFromDefinition(api.BaseParams, api.BasePath)
	if err != nil {
		return nil, err
	}
	var paramMap map[string]*Parameter
	if len(params) > 0 {
		paramMap = make(map[string]*Parameter, len(params))
		for _, p := range params {
			paramMap[p.Name] = p
		}
	}
	var consumes []string
	for _, c := range api.Consumes {
		consumes = append(consumes, c.MIMETypes...)
	}
	var produces []string
	for _, p := range api.Produces {
		produces = append(produces, p.MIMETypes...)
	}
	s := &Swagger{
		Swagger: "2.0",
		Info: &Info{
			Title:          api.Title,
			Description:    api.Description,
			TermsOfService: api.TermsOfService,
			Contact:        api.Contact,
			License:        api.License,
			Version:        "",
		},
		Host:         api.Host,
		BasePath:     api.BasePath,
		Paths:        make(map[string]*Path),
		Schemes:      api.Schemes,
		Consumes:     consumes,
		Produces:     produces,
		Parameters:   paramMap,
		Tags:         tags,
		ExternalDocs: docsFromDefinition(api.Docs),
	}

	err = api.IterateResponses(func(r *design.ResponseDefinition) error {
		res, err := responseSpecFromDefinition(s, api, r)
		if err != nil {
			return err
		}
		if s.Responses == nil {
			s.Responses = make(map[string]*Response)
		}
		s.Responses[r.Name] = res
		return nil
	})
	if err != nil {
		return nil, err
	}
	err = api.IterateResources(func(res *design.ResourceDefinition) error {
		return res.IterateActions(func(a *design.ActionDefinition) error {
			for _, route := range a.Routes {
				if err := buildPathFromDefinition(s, api, route); err != nil {
					return err
				}
			}
			return nil
		})
	})
	if err != nil {
		return nil, err
	}
	if len(genschema.Definitions) > 0 {
		s.Definitions = make(map[string]*genschema.JSONSchema)
		for n, d := range genschema.Definitions {
			// sad but swagger doesn't support these
			d.Media = nil
			d.Links = nil
			s.Definitions[n] = d
		}
	}
	return s, nil
}