# Golang Swagger > Documentación OpenAPI/Swagger en Go con swaggo/swag: anotaciones, `swag init`, integraciones con gin/echo/fiber/chi/net/http, seguridad y etiquetas de struct. Fuente: https://skillsagentes.com/skills/samber/cc-skills-golang/golang-swagger Markdown: https://skillsagentes.com/skills/samber/cc-skills-golang/golang-swagger.md Repositorio: https://github.com/samber/cc-skills-golang Autor: samber Licencia: MIT Actualizado: el mes pasado Coste de contexto: 143 tok instalada, 2.3k tok al activarse, 6.2k tok con todos los archivos del bundle Bundle: 3 archivos, 24 KB Permisos que pide: 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 bash(godig:*) bash(gopls:*) lsp mcp__gopls__* ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add samber/cc-skills-golang --skill golang-swagger --agent claude-code # Cursor npx -y skills add samber/cc-skills-golang --skill golang-swagger --agent cursor # Codex npx -y skills add samber/cc-skills-golang --skill golang-swagger --agent codex # Gemini CLI npx -y skills add samber/cc-skills-golang --skill golang-swagger --agent gemini # Windsurf npx -y skills add samber/cc-skills-golang --skill golang-swagger --agent windsurf # Cline npx -y skills add samber/cc-skills-golang --skill golang-swagger --agent cline ``` ## Qué hace - Genera y mantiene documentación Swagger/OpenAPI con swaggo/swag mediante anotaciones en comentarios (@Summary, @Param, @Success, @Router, @Security) - Ejecuta `swag init` para generar docs/ y conecta el endpoint Swagger UI según el framework (gin, echo, fiber, chi, net/http) - Define esquemas de seguridad (Bearer/JWT, OAuth2, API key, Basic auth) y los aplica a endpoints - Enriquece structs con etiquetas (swaggertype, enums, example, swaggerignore) - Revisa anotaciones existentes para completitud, corrección y cobertura de seguridad ## Cuándo usarla - Al añadir o mantener documentación Swagger/OpenAPI en un proyecto Go - Cuando el código importa github.com/swaggo/swag, gin-swagger, echo-swagger, http-swagger o files ## Cuándo no - Para gRPC, donde se usa grpc-gateway con su propio generador OpenAPI en lugar de swag ## Qué la activa - "Añade documentación Swagger a mis endpoints de Gin" - "Genera las anotaciones @Param y @Success para este handler" - "Configura la seguridad Bearer en mi API con swag" - "Revisa si mis anotaciones swagger están completas" ## Antes de instalar - Requiere los binarios go y swag (instalable con `go install github.com/swaggo/swag/cmd/swag@latest`). - makes network requests ## Archivos - SKILL.md — 9 KB - evals/evals.json — 11 KB - references/swag-cli.md — 5 KB ## SKILL.md Reproducido tal cual desde samber/cc-skills-golang bajo MIT. Esta sección es el documento original y está en inglés. **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. **Dependencies:** - swag: `go install github.com/swaggo/swag/cmd/swag@latest` ## 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 "" [attributes]` | `` | 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 {} ""` | `` | 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 ` 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. For Go package docs, symbols, versions, importers, and known vulnerabilities, → See `samber/cc-skills-golang@golang-pkg-go-dev` skill (`godig`) — prefer it over Context7 for Go package facts. To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See `samber/cc-skills-golang@golang-gopls` skill (`gopls`). Context7 remains a fallback for docs not indexed on pkg.go.dev. If you encounter a bug or unexpected behavior in swag, open an issue at . ## Dónde encaja - Categoría: [Desarrollo de APIs](https://skillsagentes.com/categorias/desarrollo-apis.md) — Diseña, prueba y documenta APIs HTTP y GraphQL. - Creador: [samber](https://skillsagentes.com/creators/samber.md) — 0 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Golang Lint](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-lint.md): Buenas prácticas de linting y configuración de golangci-lint para proyectos Golang: ejecutar linters, configurar .golangci.yml, suprimir avisos con nolint, interpretar salidas y elegir linters. - [Golang How To](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-how-to.md): Orquestador de skills de Golang, siempre activo en cualquier tarea de código, revisión, debug o setup: carga las skills más relevantes de samber/cc-skills-golang, a menudo varias a la vez. - [Golang Benchmark](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-benchmark.md): Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI. - [Golang Testing](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-testing.md): Tests de Golang listos para producción: table-driven, suites y mocks con testify, tests paralelos, fuzzing, fixtures, detección de fugas de goroutines con goleak, snapshot testing, cobertura, tests de integración. - [Golang Performance](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-performance.md): Patrones y metodología de optimización de rendimiento en Golang: si hay cuello de botella X, aplica el patrón Y, una vez que profiling o benchmarks ya lo identificaron. ## Skills relacionadas - [Golang Graphql](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-graphql.md): Implementa APIs GraphQL en Golang con gqlgen o graphql-go: diseño de schemas, resolvers, suscripciones e integración con servicios HTTP en Go. - [Golang Grpc](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-grpc.md): Ofrece guías de uso de gRPC, organización de protobuf y patrones listos para producción en microservicios Golang: servidores/clientes, proto files, interceptores, códigos de error, TLS/mTLS, bufconn y streaming. - [Golang Uber Dig](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-uber-dig.md): Implementa inyección de dependencias en Golang con uber-go/dig: contenedor basado en reflexión, Provide/Invoke, dig.In/dig.Out, valores nombrados, value groups, dependencias opcionales, scopes y Decorate. - [Golang Safety](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-safety.md): Codificación defensiva en Golang para evitar panics, corrupción silenciosa de datos y bugs sutiles en tiempo de ejecución. - [Golang Samber Hot](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-samber-hot.md): Caché en memoria en Golang con samber/hot: algoritmos de expulsión (LRU, LFU, TinyLFU, S3FIFO, ARC, TwoQueue, SIEVE, FIFO), TTL, loaders, sharding y métricas Prometheus. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)