Usage as a library
The most direct way to use codescan is to import it and call Run from your
own Go program — a generator, a go:generate step, or a test that keeps your
spec in sync with the source.
Annotate your source
Annotations are special comments following the go-swagger
convention (swagger:meta, swagger:route, swagger:model,
swagger:parameters, swagger:response, …).
A package-level swagger:meta block carries the top-level metadata of the
spec:
// Package petstore Petstore API
//
// A tiny pet store, used to demonstrate codescan annotations: the package
// comment is a `swagger:meta` block carrying the top-level metadata of the
// generated specification (title, description, version, base path, …).
//
// Schemes: https
// Version: 1.0.0
// BasePath: /v1
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// swagger:metaFull source: docs/examples/petstore/doc.go
A swagger:model annotation turns a Go struct into a definition; field-level
comments become validations and descriptions:
// Pet is a single pet in the store.
//
// swagger:model Pet
type Pet struct {
// The id of the pet.
//
// required: true
// minimum: 1
ID int64 `json:"id"`
// The name of the pet.
//
// required: true
// min length: 1
Name string `json:"name"`
// The tags associated with this pet.
Tags []string `json:"tags,omitempty"`
}Full source: docs/examples/petstore/pet.go
Run the scanner
Point codescan at the package(s) to scan. Patterns are relative go list-style
patterns, resolved against WorkDir:
opts := &codescan.Options{
WorkDir: workDir, // module root to resolve patterns from
Packages: []string{"./petstore"}, // relative package pattern
ScanModels: true, // also emit definitions for swagger:model types
}
doc, err := codescan.Run(opts)
if err != nil {
return nil, err
}Full source: docs/examples/basic/scan.go
The returned *spec.Swagger is the standard
github.com/go-openapi/spec
document — marshal it to JSON or YAML, feed it to a validator, or merge it onto
an existing spec via Options.InputSpec.
Options worth knowing
| Field | Effect |
|---|---|
Packages | Relative go list patterns to scan (e.g. ./...). |
WorkDir | Directory the patterns resolve against. |
ScanModels | Also emit definitions for swagger:model types. |
InputSpec | Overlay: merge discoveries on top of an existing spec. |
BuildTags, Include/Exclude | Scope control over what gets scanned. |
RefAliases, TransparentAliases, DescWithRef | Alias-handling knobs. |
SkipExtensions | Suppress x-go-* vendor extensions. |
See the godoc for the full list.
Next
- Tutorials — the worked, by-concept version of the above, each with the spec it produces.
- Annotation index — every annotation at a glance, linked to its example and its full reference.
- Maintainers reference — the complete annotation vocabulary, keywords, and grammar.