agentleFS
muratmirgunmuratmirgun/gophers/skills/go-swagger/SKILL.md

go-swagger

Skill9 starsChanged 4 months agoMITView on GitHub

Use when adding or maintaining OpenAPI/Swagger documentation for a Go HTTP API. Covers swaggo/swag annotation comments (@Summary, @Param, @Success, @Router, @Security), the swag CLI workflow, framework integration for Gin/Echo/Fiber/Chi/net-http, security definitions (Bearer/JWT, OAuth2, API key), and struct tags (example, enums, swaggertype, swaggerignore). Apply when a project imports github.com/swaggo/swag or any of the swaggo UI adapters, or when you need to expose /swagger/index.html.

  • Installs packages

The file

We split this skill into the rules it gives an agent

5 rules. About 0 are common, 1 is distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Annotations live next to handlers: Not in a separate docs/ folder — comments rot when separated from code.

    line 16
  2. Very specific:

    Security definitions match implementation: If the API enforces JWT, declare @securityDefinitions.apikey Bearer and annotate every protected …

    line 20
  3. Distinctive:

    Import the generated spec:

    line 51
  4. Very specific:

    Place in the file passed via -g (usually main.go):

    line 62
  5. Very specific:

    Run make check-docs in CI to catch annotation drift before merge.

    line 153

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Go Swagger / OpenAPI with swaggo

github.com/swaggo/swag is the de-facto annotation-driven OpenAPI generator for Go. You annotate handlers with // @... comments, run the swag CLI, and get docs/swagger.json, docs/swagger.yaml, and docs/docs.go for the UI.

Core Rules

  1. Docs are a contract. A field documented as required is the API's promise; a mismatch with the implementation is a bug.
  2. Annotations live next to handlers. Not in a separate docs/ folder — comments rot when separated from code.
  3. Regenerate on every change. swag init is part of the build (go generate or a Makefile target). Stale docs/ is worse than no docs.
  4. The docs package must be imported. A blank import (_ "yourmod/docs") registers the spec at process start.
  5. Use named structs for request/response bodies. swag cannot derive a schema from map[string]any or a primitive type.
  6. Security definitions match implementation. If the API enforces JWT, declare @securityDefinitions.apikey Bearer and annotate every protected endpoint with @Security Bearer.

Install and Bootstrap

go install github.com/swaggo/swag/cmd/swag@latest
swag init                              # general info from main.go
swag init -g cmd/api/main.go           # custom main path
swag fmt                               # format annotation comments like gofmt

Wire the UI for your framework — choose one:

// Gin
import (
    swaggerFiles "github.com/swaggo/files"
    ginSwagger  "github.com/swaggo/gin-swagger"
)
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

// Echo
r.GET("/swagger/*", echoSwagger.WrapHandler)

// Fiber
app.Get("/swagger/*", fiberSwagger.WrapHandler(swaggerFiles.Handler))

// Chi / net/http
mux.Handle("/swagger/", httpSwagger.Handler(swaggerFiles.Handler))

Import the generated spec:

import _ "github.com/acme/myapi/docs"          // blank: just register
import docs "github.com/acme/myapi/docs"       // named: override host at runtime

Read references/swag-cli.md for the CLI flag inventory and Makefile patterns.

General API Info

Place in the file passed via -g (usually main.go):

// @title           Orders API
// @version         1.0
// @description     Orders, customers, shipments.
// @contact.name    API Support
// @contact.email   api@acme.example
// @license.name    Apache-2.0
// @host            api.acme.example
// @BasePath        /api/v1
// @schemes         https http

// @securityDefinitions.apikey Bearer
// @in   header
// @name Authorization
// @description Use "Bearer <token>"

For multi-environment deployments, set host/basepath at runtime instead of hard-coding:

import docs "github.com/acme/myapi/docs"

func main() {
    docs.SwaggerInfo.Host     = os.Getenv("API_HOST")
    docs.SwaggerInfo.BasePath = "/api/v1"
    // ...
}

Operation Annotations

// GetOrder godoc
// @Summary      Get an order by ID
// @Tags         orders
// @Produce      json
// @Param        id   path  string  true  "Order ID (UUID)"
// @Success      200  {object}  api.OrderResponse
// @Failure      404  {object}  api.ErrorResponse
// @Router       /orders/{id} [get]
// @Security     Bearer
func GetOrder(c *gin.Context) { /* ... */ }

@Param: @Param <name> <in> <type> <required> "<desc>" [attributes] — <in> is one of path, query, body, header, formData. Useful attributes: default(v), minimum(n), maximum(n), Enums(a,b,c), example(v), collectionFormat(multi).

@Success / @Failure: @<kw> <code> {<kind>} <type> "<desc>" — {object} (struct), {array} (slice), or a primitive (string, integer). Generics (swag v2): api.Response[model.Order]. Composition: api.Response{data=model.Order}.

Read references/annotations.md for the full annotation grammar, edge cases, and security definitions.

Security

Declare schemes once globally (@securityDefinitions.apikey Bearer, @securityDefinitions.oauth2.authorizationCode, @securityDefinitions.basic) and apply per endpoint:

// @Security Bearer
// @Security OAuth2[read, write]
// @Security BasicAuth && Bearer   // both required (AND)

Endpoints without @Security are documented as public — match the implementation.

Struct Tags

Enrich models without changing their Go type. Common tags: example, enums:"a,b,c", minimum/maximum, minLength/maxLength, format, swaggertype (override detected type, e.g. time.Time → string), swaggerignore:"true", and extensions:"x-nullable,x-deprecated=true".

type CreateOrderRequest struct {
    Status   string    `json:"status" enums:"pending,paid,shipped"`
    Total    int64     `json:"total" minimum:"0" example:"19999"`
    PlacedAt time.Time `json:"placed_at" swaggertype:"string" format:"date-time"`
    Internal string    `json:"-" swaggerignore:"true"`
}

Read references/struct-tags.md for type overrides (time.Time, uuid.UUID, decimal.Decimal, custom scalars) and NULL handling.

Make Target

.PHONY: docs
docs:
	swag fmt
	swag init -g cmd/api/main.go --parseDependency --parseInternal

check-docs: docs
	@git diff --quiet docs || (echo "docs/ is stale; run make docs"; exit 1)

Run make check-docs in CI to catch annotation drift before merge.

Anti-Patterns

Anti-patternWhy it hurtsDo this instead
Forgetting _ "yourmod/docs"UI loads empty, no errorsAdd the blank import in main
@Param body stringswag cannot derive a schema from a primitiveUse a named struct
Stale docs/ after handler changeDocs lie to clientsRegenerate in CI; fail on drift
General info in wrong fileSpec has no title/hostUse -g <file> or move to main
{object} map[string]anyswag silently emptyDefine a wrapper struct
No @Security on protected routeUI shows no lock iconAdd @Security everywhere auth is required
Multi-word @Tags unquotedTags split on whitespaceQuote: @Tags "order management"
Exposing /swagger/* in production unconditionallyPublic API surface mapGate behind env flag or auth

Verification Checklist

  • swag init runs clean (no warnings)
  • docs/ is committed and up-to-date with handlers
  • Every handler has @Summary, @Router, and at least one @Success
  • Every protected handler has @Security
  • Request bodies are named structs (no map, no primitives)
  • Generic / nested response wrappers are spelled correctly (Response[T] or Response{data=T})
  • /swagger/* is gated in production (env flag or auth middleware)
  • CI fails when docs/ drifts from annotations

References

  • references/swag-cli.md — CLI flags, parsing options, Makefile patterns
  • references/annotations.md — full annotation grammar with examples
  • references/struct-tags.md — type overrides, time/UUID/decimal handling
  • references/anti-patterns.md — detailed walkthrough of each failure mode

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.