feat: add golang-swagger skill (swaggo/swag v2) (#31)

* feat: add golang-swagger skill

Covers swaggo/swag v2.0.0-rc5 — general API info annotations, operation
annotations (@Summary, @Param, @Success, @Router, @Security), security
definitions (Bearer/JWT, OAuth2, API key, Basic), struct tags (swaggertype,
enums, example, swaggerignore), and framework integrations (gin, echo,
fiber, chi, net/http).

Includes references/swag-cli.md with full CLI flag reference, dynamic
config, generics, nested composition, response headers, and MIME aliases.

* chore(golang-swagger): format, lint, token counts, README, evals

- Fix bare URL lint error (MD034)
- Update README: , token counts (desc=144, SKILL.md=2125, dir=3123)
- Add 12 adversarial evals (60 assertions) covering: blank import trap,
  body param struct requirement, swaggertype for time.Time/[]byte, Chi
  integration via http-swagger, AND security condition, -g flag for
  general info file, godoc comment for swag fmt, collectionFormat(multi),
  runtime docs.SwaggerInfo override, nested composition, enums/min/max
  struct tags, swaggerignore

* chore: bump plugin version to 1.4.0

* Revert "chore: bump plugin version to 1.4.0"

This reverts commit 72f3669199.

* eval(golang-swagger): add evaluation results — 58/60 with skill, 43/60 without (+25pp)

12 adversarial evals (60 assertions). Key discriminating evals:
- swaggertype-overrides: 5/5 vs 1/5 (time.Time + []byte traps)
- map-response-type: 5/5 vs 3/5 (raw map in @Success)
- nested-composition: 5/5 vs 3/5 (Envelope{data=model.User} syntax)
- csv-vs-multi: 4/5 vs 2/5 (collectionFormat discrimination)
- blank-import + swaggerignore: each 5/5 vs 4/5

Evals 4 (Chi+env) and 9 (conditional toggle) score 5/5 in both
conditions — common knowledge. Eval 11 (example tag) misses in both
— coverage gap noted for future iteration.

* fix(golang-swagger): use named docs import when overriding SwaggerInfo
This commit is contained in:
Samuel Berthe
2026-05-01 03:32:21 +02:00
committed by GitHub
parent 2e80a545f5
commit 556f2414fa
5 changed files with 587 additions and 3 deletions
+92 -1
View File
@@ -14,6 +14,7 @@
| Skill | Version | Assertions | With Skill | Without Skill | Delta | Uplift | Concern |
| ------------------------------- | ------- | ---------- | ---------- | ------------- | --------- | --------- | --------------------------- |
| `golang-naming` | v1.0.0 | 51 | 94% | **71%** | +24pp | 1.32× | **Low delta, high without** |
| `golang-swagger` | v1.0.0 | 60 | 97% | **72%** | +25pp | 1.35× | **Low delta, high without** |
| `golang-error-handling` | v1.0.0 | 60 | 98% | **72%** | +27pp | 1.36× | **Low delta, high without** |
| `golang-popular-libraries` | v1.0.0 | 54 | 100% | **70%** | +30pp | 1.43× | **Low delta, high without** |
| `golang-security` | v1.0.0 | 110 | 100% | **68%** | +32pp | 1.47× | **Low delta, high without** |
@@ -50,7 +51,7 @@
| `golang-uber-fx` | v1.0.0 | 21 | 100% | **95%** | +5pp | 1.05× | **Low delta, high without** |
| `golang-uber-dig` | v1.0.0 | 20 | 100% | **90%** | +10pp | 1.11× | **Low delta, high without** |
| `golang-samber-do` | v1.0.0 | 53 | 100% | 19% | +81pp | 5.26× | |
| **Total (37 skills)** | | **3182** | **98%** | **55%** | **+43pp** | **1.78×** | |
| **Total (38 skills)** | | **3242** | **98%** | **55%** | **+43pp** | **1.79×** | |
## `golang-naming` — v1.0.0
@@ -4501,4 +4502,94 @@
</details>
## `golang-swagger` — v1.0.0
| | With Skill | Without Skill | Delta |
| ----------- | --------------- | --------------- | --------- |
| **Overall** | **58/60 (97%)** | **43/60 (72%)** | **+25pp** |
<details>
<summary>Full breakdown (60 assertions)</summary>
**Model:** Claude Sonnet 4.6 | **Runs:** 12 evals × 2 configs = 24 subagents | **Grading:** LLM-as-judge
| # | Assertion | With | Without |
| ---- | ------------------------------------------------------------------------------------------------------- | ------------------------------ | ------------------------------ |
| | **1. gin-blank-import** — blank import + ginSwagger wire-up | **<span class="g">5/5</span>** | **<span class="r">4/5</span>** |
| 1.1 | Adds a blank import of the docs package (e.g., `_ "<module>/docs"`) | <span class="g">✓</span> | <span class="r">✗</span> |
| 1.2 | Imports github.com/swaggo/gin-swagger | <span class="g">✓</span> | <span class="g">✓</span> |
| 1.3 | Imports github.com/swaggo/files | <span class="g">✓</span> | <span class="g">✓</span> |
| 1.4 | Registers a GET route matching /swagger/*any using ginSwagger.WrapHandler | <span class="g">✓</span> | <span class="g">✓</span> |
| 1.5 | Does not suggest running swag init again (it was already done) | <span class="g">✓</span> | <span class="g">✓</span> |
| | **2. map-response-type** — map[string]bool cannot be used directly in @Success | **<span class="g">5/5</span>** | **<span class="r">3/5</span>** |
| 2.1 | Does NOT use `{object} map[string]bool` directly in @Success | <span class="g">✓</span> | <span class="r">✗</span> |
| 2.2 | Defines a named struct for the response OR acknowledges a swaggertype workaround is needed | <span class="g">✓</span> | <span class="r">✗</span> |
| 2.3 | @Success annotation uses a named type (not a raw map literal) | <span class="g">✓</span> | <span class="r">✗</span> |
| 2.4 | @Router annotation is present with [get] method | <span class="g">✓</span> | <span class="g">✓</span> |
| 2.5 | @Produce annotation specifies json | <span class="g">✓</span> | <span class="g">✓</span> |
| | **3. swaggertype-overrides** — time.Time and []byte need swaggertype tags | **<span class="g">5/5</span>** | **<span class="r">1/5</span>** |
| 3.1 | Adds swaggertype tag to CreatedAt field | <span class="g">✓</span> | <span class="r">✗</span> |
| 3.2 | Adds swaggertype tag to UpdatedAt field with the same treatment | <span class="g">✓</span> | <span class="r">✗</span> |
| 3.3 | Adds swaggertype:"string" and format:"base64" to the Payload []byte field | <span class="g">✓</span> | <span class="r">✗</span> |
| 3.4 | Preserves the json tags (does not remove them) | <span class="g">✓</span> | <span class="g">✓</span> |
| 3.5 | Does not leave time.Time fields without any swaggertype override | <span class="g">✓</span> | <span class="r">✗</span> |
| | **4. chi-dynamic-basepath** — Chi router + BasePath from env var | **<span class="g">5/5</span>** | **<span class="g">5/5</span>** |
| 4.1 | Imports github.com/swaggo/http-swagger | <span class="g">✓</span> | <span class="g">✓</span> |
| 4.2 | Uses r.Get (chi method) to register the swagger route with a wildcard pattern | <span class="g">✓</span> | <span class="g">✓</span> |
| 4.3 | Sets docs.SwaggerInfo.BasePath using os.Getenv("API_BASE_PATH") or equivalent | <span class="g">✓</span> | <span class="g">✓</span> |
| 4.4 | Includes the blank docs import | <span class="g">✓</span> | <span class="g">✓</span> |
| 4.5 | Does not suggest rebuilding or running swag init per environment | <span class="g">✓</span> | <span class="g">✓</span> |
| | **5. and-security-condition** — && vs two separate @Security lines | **<span class="g">5/5</span>** | **<span class="r">4/5</span>** |
| 5.1 | Uses && between security schemes on a single @Security annotation line | <span class="g">✓</span> | <span class="r">✗</span> |
| 5.2 | Does NOT write two separate @Security lines for AND semantics | <span class="g">✓</span> | <span class="g">✓</span> |
| 5.3 | References valid security definition names (ApiKeyAuth, BasicAuth, or similar) | <span class="g">✓</span> | <span class="g">✓</span> |
| 5.4 | Explains or implies that two separate @Security lines would mean OR, not AND | <span class="g">✓</span> | <span class="g">✓</span> |
| 5.5 | @Security line appears inside the handler doc comment block | <span class="g">✓</span> | <span class="g">✓</span> |
| | **6. tag-exclusion** — swag init --tags with ! prefix to exclude tags | **<span class="g">5/5</span>** | **<span class="r">4/5</span>** |
| 6.1 | Uses the --tags flag (or -t) with swag init | <span class="g">✓</span> | <span class="g">✓</span> |
| 6.2 | Uses ! prefix to exclude tags (e.g., --tags '!Internal,!Admin' or similar) | <span class="g">✓</span> | <span class="r">✗</span> |
| 6.3 | Shows a complete swag init command | <span class="g">✓</span> | <span class="g">✓</span> |
| 6.4 | Does not suggest manually editing the generated swagger.json | <span class="g">✓</span> | <span class="g">✓</span> |
| 6.5 | Does not require writing custom Go code to filter endpoints | <span class="g">✓</span> | <span class="g">✓</span> |
| | **7. godoc-comment-swag-fmt** — godoc comment line required for swag fmt | **<span class="g">5/5</span>** | **<span class="r">4/5</span>** |
| 7.1 | Adds `// CreateOrder godoc` as the first line of the comment block | <span class="g">✓</span> | <span class="r">✗</span> |
| 7.2 | godoc comment appears before any @ annotation | <span class="g">✓</span> | <span class="g">✓</span> |
| 7.3 | At minimum includes @Summary, @Router annotations | <span class="g">✓</span> | <span class="g">✓</span> |
| 7.4 | @Router specifies both path and HTTP method | <span class="g">✓</span> | <span class="g">✓</span> |
| 7.5 | Annotation block is placed directly above the function signature | <span class="g">✓</span> | <span class="g">✓</span> |
| | **8. csv-vs-multi** — collectionFormat(multi) for ids, collectionFormat(csv) for fields | **<span class="r">4/5</span>** | **<span class="r">2/5</span>** |
| 8.1 | @Param for ids uses collectionFormat(multi) | <span class="g">✓</span> | <span class="r">✗</span> |
| 8.2 | @Param for fields uses collectionFormat(csv) or omits it (csv is the default) | <span class="r">✗</span> | <span class="r">✗</span> |
| 8.3 | Both params use []string or []int as data type | <span class="g">✓</span> | <span class="g">✓</span> |
| 8.4 | Both params are marked as not required (false) | <span class="g">✓</span> | <span class="g">✓</span> |
| 8.5 | @Router annotation is present with [get] method | <span class="g">✓</span> | <span class="r">✗</span> |
| | **9. conditional-swagger** — env-based swagger toggle without build tags | **<span class="g">5/5</span>** | **<span class="g">5/5</span>** |
| 9.1 | Uses os.Getenv (or equivalent) to read APP_ENV at runtime | <span class="g">✓</span> | <span class="g">✓</span> |
| 9.2 | Conditionally registers the swagger route only when not in production | <span class="g">✓</span> | <span class="g">✓</span> |
| 9.3 | Does not require separate builds or build tags | <span class="g">✓</span> | <span class="g">✓</span> |
| 9.4 | The blank docs import is still present (or acknowledged as needed) | <span class="g">✓</span> | <span class="g">✓</span> |
| 9.5 | Solution works without recompiling between environments | <span class="g">✓</span> | <span class="g">✓</span> |
| | **10. nested-composition** — Envelope{data=model.User} nested composition syntax | **<span class="g">5/5</span>** | **<span class="r">3/5</span>** |
| 10.1 | @Success annotation uses nested composition syntax with curly braces (e.g., Envelope{data=model.User}) | <span class="g">✓</span> | <span class="r">✗</span> |
| 10.2 | The inner type is the User struct (or equivalent named type) | <span class="g">✓</span> | <span class="r">✗</span> |
| 10.3 | Does not create a new wrapper struct just for documentation purposes | <span class="g">✓</span> | <span class="g">✓</span> |
| 10.4 | @Param for the id path parameter is present with path location | <span class="g">✓</span> | <span class="g">✓</span> |
| 10.5 | @Router specifies the correct path and [get] method | <span class="g">✓</span> | <span class="r">✗</span> |
| | **11. enums-min-max-tags** — enums/minimum/maximum struct tags | **<span class="r">4/5</span>** | **<span class="r">4/5</span>** |
| 11.1 | Adds `enums:"admin,editor,viewer"` struct tag to Role field | <span class="g">✓</span> | <span class="g">✓</span> |
| 11.2 | Adds `minimum:"0"` and `maximum:"100"` struct tags to Score field | <span class="g">✓</span> | <span class="g">✓</span> |
| 11.3 | Adds json tags to all fields | <span class="g">✓</span> | <span class="g">✓</span> |
| 11.4 | Adds example tags to at least one field | <span class="r">✗</span> | <span class="r">✗</span> |
| 11.5 | Does not only describe constraints in a comment — they must be machine-readable struct tags | <span class="g">✓</span> | <span class="g">✓</span> |
| | **12. swaggerignore-serialization** — swaggerignore:"true" vs json:"-" | **<span class="g">5/5</span>** | **<span class="r">4/5</span>** |
| 12.1 | Uses swaggerignore:"true" on the LastModified field | <span class="g">✓</span> | <span class="r">✗</span> |
| 12.2 | Keeps a valid json tag on LastModified (NOT json:"-") | <span class="g">✓</span> | <span class="g">✓</span> |
| 12.3 | Does NOT suggest removing the field from the struct | <span class="g">✓</span> | <span class="g">✓</span> |
| 12.4 | Other struct fields retain their json and swagger documentation | <span class="g">✓</span> | <span class="g">✓</span> |
| 12.5 | Explains or implies why json:"-" would be wrong here (breaks serialization) | <span class="g">✓</span> | <span class="g">✓</span> |
**Analyst pass:** The skill shows clear uplift on annotation mechanics that require knowing non-obvious swag behaviors: blank import requirement (eval 1), map type limitations (eval 2), swaggertype overrides for time.Time and []byte (eval 3), nested composition syntax (eval 10), and swaggerignore vs json:"-" (eval 12). Evals 4 (Chi+env) and 9 (conditional toggle) scored 5/5 in both conditions — the model already knows how to read env vars and register Chi routes, so these evals test common knowledge rather than skill uplift. Eval 11 shows a consistent miss on the `example:` struct tag in both conditions, indicating a coverage gap rather than discrimination; the skill should add an explicit example on `example:` struct tag usage. Future iterations should also target less-known swag behaviors: `@extensions`, `@x-` custom properties, multi-file init patterns (`--dir` flag), and OpenAPI 3.0 output.
</details>
<!-- prettier-ignore-end -->
+2 -2
View File
@@ -183,7 +183,7 @@ These skills are designed as **atomic, cross-referencing units**. A skill may re
| ✅ `golang-grpc` | ⚡ | -41% | 69 | 2,149 | 4,965 |
| ❌ `golang-spf13-cobra` | | — | 0 | 0 | 0 |
| ❌ `golang-spf13-viper` | | — | 0 | 0 | 0 |
| `golang-swagger` | | — | 0 | 0 | 0 |
| `golang-swagger` | | — | 144 | 2,125 | 3,123 |
| ✅ `golang-uber-dig` | ⚡ | -10% | 107 | 2,264 | 5,904 |
| ✅ `golang-uber-fx` | ⚡ | -5% | 118 | 2,499 | 6,747 |
| ✅ `golang-samber-do` | ⚡ | -81% | 70 | 1,746 | 3,269 |
@@ -200,7 +200,7 @@ These skills are designed as **atomic, cross-referencing units**. A skill may re
| | With Skill | Without Skill | Delta |
| ----------- | ------------------- | ------------------- | --------- |
| **Overall** | **3106/3182 (98%)** | **1729/3182 (54%)** | **+44pp** |
| **Overall** | **3164/3242 (98%)** | **1772/3242 (55%)** | **+43pp** |
See [EVALUATIONS.md](./EVALUATIONS.md) for the full per-skill breakdown.
+224
View File
@@ -0,0 +1,224 @@
---
name: golang-swagger
description: "Golang OpenAPI/Swagger documentation with swaggo/swag — annotation comments (@Summary, @Param, @Success, @Router, @Security), swag init code generation, framework integrations (gin, echo, fiber, chi, net/http), security definitions (Bearer/JWT, OAuth2, API key), and struct tags (swaggertype, enums, example, swaggerignore). Apply when adding or maintaining Swagger/OpenAPI docs in a Go project, or when the codebase imports github.com/swaggo/swag, github.com/swaggo/gin-swagger, github.com/swaggo/echo-swagger, github.com/swaggo/http-swagger, or github.com/swaggo/files."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code or similar AI coding agents. Requires go and swag CLI.
metadata:
author: samber
version: "1.0.0"
openclaw:
emoji: "📋"
homepage: https://github.com/samber/cc-skills-golang
requires:
bins:
- go
- swag
install:
- kind: go
package: github.com/swaggo/swag/cmd/swag@latest
bins: [swag]
skill-library-version: "2.0.0-rc5"
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent WebFetch mcp__context7__resolve-library-id mcp__context7__query-docs Bash(swag:*) AskUserQuestion
---
**Persona:** You are a Go API documentation engineer. You treat docs as a contract — accurate, complete annotations prevent integration bugs and make the Swagger UI the source of truth for API consumers.
**Modes:**
- **Build** — adding Swagger to a new or existing Go project: set up the toolchain, annotate handlers, generate docs, wire the UI endpoint.
- **Audit** — reviewing existing swagger annotations for completeness, correctness, and security coverage.
## Setup
Three steps to get Swagger UI running:
```bash
swag init # generates docs/ with docs.go, swagger.json, swagger.yaml
swag init -g cmd/api/main.go # if general info is not in main.go
swag fmt # format annotation comments (like go fmt)
```
Import the `docs` package to register the spec. Use a blank import when only wiring the UI; use a named import when you also need to override `docs.SwaggerInfo` at runtime:
```go
import _ "yourmodule/docs" // blank: registers spec, no identifier
import docs "yourmodule/docs" // named: use when overriding SwaggerInfo
```
Wire the UI endpoint — pick your framework:
```go
// Gin
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
// Echo
e.GET("/swagger/*", echoSwagger.WrapHandler)
// Fiber
app.Get("/swagger/*", fiberSwagger.WrapHandler(swaggerFiles.Handler))
// net/http
mux.Handle("/swagger/", httpSwagger.Handler(swaggerFiles.Handler))
// Chi
r.Get("/swagger/*", httpSwagger.Handler(swaggerFiles.Handler))
```
Access the UI at `/swagger/index.html`.
For dynamic host/basepath (multi-environment), use a named import and override before serving:
```go
import docs "yourmodule/docs"
docs.SwaggerInfo.Host = os.Getenv("API_HOST")
docs.SwaggerInfo.BasePath = "/api/v1"
```
[Full CLI reference](references/swag-cli.md)
## General API Info
Place in `main.go` (or the file passed via `-g`). These annotations define the top-level spec:
```go
// @title My API
// @version 1.0
// @description Short description of the API.
// @host localhost:8080
// @BasePath /api/v1
// @schemes http https
// @contact.name API Support
// @contact.email support@example.com
// @license.name Apache 2.0
// @securityDefinitions.apikey Bearer
// @in header
// @name Authorization
// @description Type "Bearer" followed by a space and the JWT token.
```
## Operation Annotations
Annotate each handler function. The standard doc comment (`// FuncName godoc`) must precede swag annotations — it anchors indentation for `swag fmt`.
```go
// ShowAccount godoc
// @Summary Get account by ID
// @Description Returns account details for the given ID.
// @Tags accounts
// @Accept json
// @Produce json
// @Param id path int true "Account ID"
// @Param filter query string false "Optional search filter"
// @Success 200 {object} model.Account
// @Success 204 "No content"
// @Failure 400 {object} api.ErrorResponse
// @Failure 404 {object} api.ErrorResponse
// @Router /accounts/{id} [get]
// @Security Bearer
func ShowAccount(c *gin.Context) {}
```
**@Param** format: `@Param <name> <in> <type> <required> "<description>" [attributes]`
| `<in>` | Usage |
| ---------- | ------------------------------------ |
| `path` | URL path segment (`/users/{id}`) |
| `query` | URL query string (`?filter=x`) |
| `body` | Request body — type must be a struct |
| `header` | HTTP header |
| `formData` | Multipart/form field |
Optional attributes on `@Param`: `default(v)`, `minimum(n)`, `maximum(n)`, `minLength(n)`, `maxLength(n)`, `Enums(a,b,c)`, `example(v)`, `collectionFormat(multi)`.
**@Success/@Failure** format: `@Success <code> {<kind>} <type> "<description>"`
| `<kind>` | When |
| -------------------- | ---------------- |
| `{object}` | Single struct |
| `{array}` | Slice of structs |
| `string` / `integer` | Primitive |
**Generics** (swag v2): `@Success 200 {object} api.Response[model.User]`
**Nested composition**: `@Success 200 {object} api.Response{data=model.User}`
## Security Definitions
Define once at the API level (in main.go), apply per endpoint with `@Security`.
```go
// Bearer / JWT
// @securityDefinitions.apikey Bearer
// @in header
// @name Authorization
// API key in header
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name X-API-Key
// Basic auth
// @securityDefinitions.basic BasicAuth
// OAuth2 authorization code
// @securityDefinitions.oauth2.authorizationCode OAuth2
// @authorizationUrl https://example.com/oauth/authorize
// @tokenUrl https://example.com/oauth/token
// @scope.read Read access
// @scope.write Write access
```
Apply to an endpoint:
```go
// @Security Bearer
// @Security OAuth2[read, write]
// @Security BasicAuth && ApiKeyAuth // AND — both required
```
## Struct Tags
Enrich models without changing their Go type:
```go
type CreateUserRequest struct {
Name string `json:"name" example:"Jane Doe" minLength:"2" maxLength:"100"`
Role string `json:"role" enums:"admin,user,guest" example:"user"`
Age int `json:"age" minimum:"18" maximum:"120"`
Avatar []byte `json:"avatar" swaggertype:"string" format:"base64"`
Secret string `json:"-" swaggerignore:"true"` // excluded from docs
}
```
| Tag | Purpose |
| --- | --- |
| `example` | Example value shown in Swagger UI |
| `enums` | Comma-separated allowed values |
| `swaggertype` | Override detected type (e.g., `"primitive,integer"` for `time.Time`) |
| `swaggerignore:"true"` | Exclude field from the generated schema |
| `extensions` | Add OpenAPI extensions: `extensions:"x-nullable,x-deprecated=true"` |
## Common Mistakes
| Mistake | Why it breaks | Fix |
| --- | --- | --- |
| Missing `_ "yourmodule/docs"` import | Schema not registered; UI loads empty | Add blank import in main.go or server init |
| Stale `docs/` after code changes | Docs diverge from implementation; consumers get wrong schema | Re-run `swag init` after every annotation change |
| `@Param body` with primitive type | swag cannot derive schema from `string`; generation fails | Always use a named struct for body params |
| No `@Security` on protected routes | Swagger UI shows no lock icon; testers send unauthenticated requests | Apply `@Security` to every authenticated endpoint |
| General info annotations in the wrong file | swag silently skips them; spec has no title/host | Use `-g <file>` flag or move annotations to `main.go` |
| Using `{object}` with a map type | swag cannot generate a schema for `map[string]any` without help | Use a named struct or annotate with `swaggertype` |
| Multi-word `@Tags` without quotes | Tags split on spaces, producing malformed grouping | Quote tags with spaces: `@Tags "user accounts"` |
## Cross-References
- → See `samber/cc-skills-golang@golang-security` for securing the Swagger UI endpoint in production (disable or gate with auth middleware).
- → See `samber/cc-skills-golang@golang-grpc` for gRPC — use grpc-gateway with its own OpenAPI generator instead of swag.
This skill is not exhaustive. Refer to the swaggo/swag documentation and code examples for up-to-date API signatures and usage patterns. Context7 can help as a discoverability platform.
If you encounter a bug or unexpected behavior in swag, open an issue at <https://github.com/swaggo/swag/issues>.
+149
View File
@@ -0,0 +1,149 @@
{
"skill_name": "golang-swagger",
"evals": [
{
"id": 1,
"prompt": "I've already run `swag init` and the docs/ folder was generated. Now wire up the Swagger UI in my Gin server so the docs actually show up at /swagger/index.html. Here's my main.go:\n\n```go\npackage main\n\nimport \"github.com/gin-gonic/gin\"\n\nfunc main() {\n r := gin.Default() \n r.GET(\"/api/users\", getUsers)\n r.Run(\":8080\")\n}\n```",
"expected_output": "Adds the blank import `_ \"yourmodule/docs\"` AND wires the ginSwagger endpoint. The blank import is the trap — without it the UI loads empty even if the route is registered.",
"assertions": [
"Adds a blank import of the docs package (e.g., `_ \"<module>/docs\"`)",
"Imports github.com/swaggo/gin-swagger",
"Imports github.com/swaggo/files",
"Registers a GET route matching /swagger/*any using ginSwagger.WrapHandler",
"Does not suggest running swag init again (it was already done)"
]
},
{
"id": 2,
"prompt": "Our GET /settings endpoint returns a dynamic set of feature flags as a map: `map[string]bool`. Document this endpoint for Swagger so the response schema is visible in the UI.",
"expected_output": "Defines a named struct for the response or uses swaggertype annotation — swag cannot generate a schema for map[string]bool directly. The trap is using `{object} map[string]bool` in @Success which fails generation.",
"assertions": [
"Does NOT use `{object} map[string]bool` directly in @Success",
"Defines a named struct for the response OR acknowledges a swaggertype workaround is needed",
"@Success annotation uses a named type (not a raw map literal)",
"@Router annotation is present with [get] method",
"@Produce annotation specifies json"
]
},
{
"id": 3,
"prompt": "Document this Go struct for Swagger. We need the docs to look correct:\n\n```go\ntype AuditRecord struct {\n CreatedAt time.Time\n UpdatedAt time.Time\n Payload []byte\n}\n```",
"expected_output": "Uses swaggertype tag to override time.Time (which becomes an object by default) and []byte (which becomes a base64 string). Without the skill the model leaves the types as-is, producing wrong schemas.",
"assertions": [
"Adds swaggertype tag to CreatedAt field (e.g., `swaggertype:\"string\"` with format:\"date-time\" or `swaggertype:\"primitive,integer\"`)",
"Adds swaggertype tag to UpdatedAt field with the same treatment",
"Adds swaggertype:\"string\" and format:\"base64\" to the Payload []byte field",
"Preserves the json tags (does not remove them)",
"Does not leave time.Time fields without any swaggertype override"
]
},
{
"id": 4,
"prompt": "Set up the Swagger UI for a Chi HTTP router. The BasePath must be set dynamically from an `API_BASE_PATH` environment variable because we deploy behind different path prefixes in staging and production.",
"expected_output": "Uses github.com/swaggo/http-swagger for Chi AND sets docs.SwaggerInfo.BasePath from os.Getenv. The trap is not knowing the http-swagger package for Chi and not knowing about the runtime docs.SwaggerInfo override.",
"assertions": [
"Imports github.com/swaggo/http-swagger",
"Uses r.Get (chi method) to register the swagger route with a wildcard pattern",
"Sets docs.SwaggerInfo.BasePath using os.Getenv(\"API_BASE_PATH\") or equivalent",
"Imports the docs package (blank `_ \"<module>/docs\"` or named `docs \"<module>/docs\"`)",
"Does not suggest rebuilding or running swag init per environment"
]
},
{
"id": 5,
"prompt": "This endpoint requires BOTH an API key AND basic authentication — not one or the other. Both must be present. Show me the @Security annotation for this.",
"expected_output": "Uses the && syntax on a single @Security line. Two separate @Security lines mean OR (either is sufficient), which is wrong for AND semantics.",
"assertions": [
"Uses && between security schemes on a single @Security annotation line",
"Does NOT write two separate @Security lines for AND semantics",
"References valid security definition names (ApiKeyAuth, BasicAuth, or similar)",
"Explains or implies that two separate @Security lines would mean OR, not AND",
"@Security line appears inside the handler doc comment block"
]
},
{
"id": 6,
"prompt": "Our API has endpoints tagged with 'Internal' and 'Admin' that must not appear in the public Swagger docs we ship to customers. How do we generate a spec that excludes both of these tags?",
"expected_output": "Uses swag init --tags flag with ! prefix to exclude tags. Without the skill the model likely suggests code-level filtering, separate spec files, or post-processing the JSON rather than the built-in CLI flag.",
"assertions": [
"Uses the --tags flag (or -t) with swag init",
"Uses ! prefix to exclude tags (e.g., --tags '!Internal,!Admin' or similar)",
"Shows a complete swag init command",
"Does not suggest manually editing the generated swagger.json",
"Does not require writing custom Go code to filter endpoints"
]
},
{
"id": 7,
"prompt": "Add swagger annotations to this handler and make sure `swag fmt` formats them correctly:\n\n```go\nfunc CreateOrder(c *gin.Context) {\n // handler logic\n}\n```",
"expected_output": "Includes a standard godoc comment (// CreateOrder godoc) before the @Summary annotation. Without it swag fmt cannot determine indentation and may produce malformed output.",
"assertions": [
"Adds `// CreateOrder godoc` as the first line of the comment block",
"godoc comment appears before any @ annotation",
"At minimum includes @Summary, @Router annotations",
"@Router specifies both path and HTTP method",
"Annotation block is placed directly above the function signature"
]
},
{
"id": 8,
"prompt": "Document a GET /export endpoint with two query parameters: `ids` accepts multiple values as separate query keys (e.g., ?ids=1&ids=2&ids=3), and `fields` accepts a comma-separated list of field names (e.g., ?fields=name,email,age). Both are optional.",
"expected_output": "Uses collectionFormat(multi) for ids and collectionFormat(csv) for fields. Without the skill the model likely uses multi for both, or omits the collectionFormat attribute entirely and lets it default.",
"assertions": [
"@Param for ids uses collectionFormat(multi)",
"@Param for fields uses collectionFormat(csv) or omits it (csv is the default)",
"Both params use []string or []int as data type",
"Both params are marked as not required (false)",
"@Router annotation is present with [get] method"
]
},
{
"id": 9,
"prompt": "We want to expose the Swagger UI in development but disable it entirely in production. Our app reads `APP_ENV=production` or `APP_ENV=development`. How do we conditionally enable the swagger endpoint without separate builds or build tags?",
"expected_output": "Guards the swagger route registration behind an os.Getenv check at startup. The trap is suggesting build tags (requires separate builds) or removing the route in a middleware (more complex than needed).",
"assertions": [
"Uses os.Getenv (or equivalent) to read APP_ENV at runtime",
"Conditionally registers the swagger route only when not in production",
"Does not require separate builds or build tags",
"The blank docs import is still present (or acknowledged as needed)",
"Solution works without recompiling between environments"
]
},
{
"id": 10,
"prompt": "Our API always wraps responses in this envelope:\n\n```go\ntype Envelope struct {\n Data interface{} `json:\"data\"`\n Message string `json:\"message\"`\n}\n```\n\nDocument a GET /users/{id} endpoint that returns an Envelope where Data is a User object. The Swagger UI should show the actual User schema inside data, not just `interface{}`.",
"expected_output": "Uses nested composition syntax @Success 200 {object} Envelope{data=model.User}. Without the skill the model would document it as plain Envelope, losing the User type information in the generated schema.",
"assertions": [
"@Success annotation uses nested composition syntax with curly braces (e.g., Envelope{data=model.User})",
"The inner type is the User struct (or equivalent named type)",
"Does not create a new wrapper struct just for documentation purposes",
"@Param for the id path parameter is present with path location",
"@Router specifies the correct path and [get] method"
]
},
{
"id": 11,
"prompt": "Add swagger documentation to this struct. The Role field should only allow the values 'admin', 'editor', and 'viewer' in the Swagger UI. The Score field should be between 0 and 100.\n\n```go\ntype UserProfile struct {\n Name string\n Role string\n Score int\n}\n```",
"expected_output": "Uses enums struct tag for Role and minimum/maximum tags for Score. Without the skill the model might only describe constraints in comments or @Param descriptions.",
"assertions": [
"Adds `enums:\"admin,editor,viewer\"` struct tag to Role field",
"Adds `minimum:\"0\"` and `maximum:\"100\"` struct tags to Score field",
"Adds json tags to all fields",
"Adds example tags to at least one field",
"Does not only describe constraints in a comment — they must be machine-readable struct tags"
]
},
{
"id": 12,
"prompt": "We have a struct with a `LastModified time.Time` field used for ETag generation in middleware. This field MUST be serialized to JSON for our caching layer to work, but it should NOT appear in the Swagger UI documentation shown to API consumers.",
"expected_output": "Uses swaggerignore:\"true\" while keeping the json tag intact. The trap is using json:\"-\" which breaks JSON serialization — the model must understand that swaggerignore is the correct tool when the field must still serialize.",
"assertions": [
"Uses swaggerignore:\"true\" on the LastModified field",
"Keeps a valid json tag on LastModified (NOT json:\"-\")",
"Does NOT suggest removing the field from the struct",
"Other struct fields retain their json and swagger documentation",
"Explains or implies why json:\"-\" would be wrong here (breaks serialization)"
]
}
]
}
@@ -0,0 +1,120 @@
# swag CLI Reference
## swag init — Generate Documentation
```bash
swag init # parse main.go, generate docs/
swag init -g cmd/api/main.go # general info in a different file
swag init -d ./handlers,./models # additional directories to parse
swag init --exclude ./vendor,./internal/gen # skip directories
swag init -ot go,json # output only Go and JSON (skip YAML)
swag init -q # quiet mode (no log output)
swag init --parseInternal # include internal/ packages
swag init --parseDependency # parse vendor/module dependencies
swag init --requiredByDefault # mark all struct fields as required
swag init -p camelcase # property naming: snakecase | camelcase | pascalcase
swag init --tags Users,Products # only generate for these tags
swag init --tags '!Internal' # exclude tag (! prefix)
swag init --td "[[,]]" # custom template delimiters
```
## swag fmt — Format Annotations
```bash
swag fmt # format all annotation comments
swag fmt -d ./handlers # format specific directory
swag fmt --exclude ./vendor # skip directories
```
`swag fmt` requires a standard Go doc comment (`// FuncName godoc`) immediately before the first `@` annotation — without it the formatter cannot determine indentation.
## Framework Integration Packages
| Framework | Package |
| ------------------------ | ----------------------------------- |
| Gin | `github.com/swaggo/gin-swagger` |
| Echo | `github.com/swaggo/echo-swagger` |
| Fiber | `github.com/swaggo/fiber-swagger` |
| Chi / net/http / Gorilla | `github.com/swaggo/http-swagger` |
| Buffalo | `github.com/swaggo/buffalo-swagger` |
| Hertz | `github.com/hertz-contrib/swagger` |
The shared files package (`github.com/swaggo/files`) is required by all integrations.
## Dynamic Configuration
Override spec values at runtime — useful for multi-environment deployments where host and basepath differ between staging and production:
```go
import docs "yourmodule/docs" // named import required to access docs.SwaggerInfo
func main() {
docs.SwaggerInfo.Title = "My API"
docs.SwaggerInfo.Description = "Production API"
docs.SwaggerInfo.Version = "2.0"
docs.SwaggerInfo.Host = os.Getenv("API_HOST")
docs.SwaggerInfo.BasePath = "/api/v1"
docs.SwaggerInfo.Schemes = []string{"https"}
}
```
## Generics (swag v2)
Single type parameter:
```go
// @Success 200 {object} api.Response[model.User]
// @Success 200 {array} api.Response[model.User]
```
Multiple type parameters:
```go
// @Success 200 {object} api.Response[model.User, model.Meta]
```
## Nested Composition
Embed or override fields in the documented schema without changing Go types:
```go
// @Success 200 {object} api.Envelope{data=model.User}
// @Success 200 {object} api.Envelope{data=[]model.User}
// @Success 200 {object} api.Envelope{data=model.User,meta=api.Pagination}
```
## Response Headers
```go
// @Header 200 {string} X-Request-ID "Unique request identifier"
// @Header 200,400 {string} X-Request-ID "Unique request identifier"
// @Header all {string} X-Request-ID "Present on every response"
```
## Function-Scoped Structs
swag can parse structs defined inside handler functions:
```go
// @Param req body main.CreateUser.request true "Create user input"
func CreateUser(c *gin.Context) {
type request struct {
Name string `json:"name"`
Email string `json:"email"`
}
}
```
## MIME Type Aliases
| Alias | Content-Type |
| ----------------------- | --------------------------------- |
| `json` | application/json |
| `xml` | application/xml |
| `plain` | text/plain |
| `html` | text/html |
| `mpfd` | multipart/form-data |
| `x-www-form-urlencoded` | application/x-www-form-urlencoded |
| `octet-stream` | application/octet-stream |
| `png` / `jpeg` / `gif` | image/png, image/jpeg, image/gif |
| `event-stream` | text/event-stream |