Skip to main content
skill Claude Code CX Codex Cursor GitHub Copilot

golang-swagger — Claude Code skill: install and use

Adds guidance for OpenAPI and Swagger docs in Go through annotations and spec generation. Useful when documenting handlers or reviewing an existing API.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add samber/cc-skills-golang --skill golang-swagger -a claude-code
Open on GitHub

What golang-swagger does

This skill covers Go API documentation with swaggo/swag: handler annotations for parameters, responses, routes, and security settings. It also accounts for gin, echo, fiber, chi, and net/http integrations, plus model tags such as swaggertype, enums, example, and swaggerignore.

The workflow uses swag init and swag fmt; swag init -g cmd/api/main.go handles projects where the general API information is elsewhere. The skill guides the agent through importing the generated docs package, wiring a Swagger UI endpoint, and setting docs.SwaggerInfo.Host or BasePath. Check that go and the swag CLI are available first.

It covers two modes: building Swagger documentation for a Go project and auditing existing annotations for completeness and security coverage. Bearer/JWT, OAuth2, and API key definitions are included.

What it helps with

  • annotate Go handlers for Swagger
  • generate the docs/ directory with swag init
  • wire Swagger UI into a Go HTTP framework
  • define Bearer/JWT or OAuth2 security
  • audit @Param and @Security annotations

Example prompts for the agent

  • Add Swagger annotations to the handlers in this Go project and generate the API docs.
  • Review the existing `@Param`, `@Success`, `@Failure`, `@Router`, and `@Security` annotations, then run `swag fmt`.
  • Set up Swagger UI for `gin` and run `swag init -g cmd/api/main.go`.

How to install golang-swagger

1Skills CLI (Vercel)

npx skills add samber/cc-skills-golang --skill golang-swagger -a claude-code

2Manually: put the files in place

~/.claude/skills/golang-swagger/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/golang-swagger/

From the same set32

The whole set →
golang-code-style samber A skill for writing clear Go code: line breaking, variable declarations, control flow, when comments help. Use it when writing or reviewing Go, discussing style, or setting project standards. Claude Code CX Codex Cursor +1 44,000installs golang-error-handling samber Skill for idiomatic Go error handling: wrapping with context, chain inspection, structured logging, and samber/oops integration. Apply when creating, wrapping, inspecting, or logging errors in Go code. Claude Code CX Codex Cursor +1 43,200installs golang-security samber Identifies Go vulnerabilities, models threats with STRIDE and DREAD, and fixes injections, secret leaks, and cryptography flaws. Claude Code CX Codex Cursor +1 42,100installs golang-design-patterns samber This skill guides idiomatic Go design for APIs, resource lifecycles, graceful shutdown, and architecture. Use it when designing or reviewing Go code. Claude Code CX Codex Cursor +1 41,900installs golang-performance samber Guides AI coding agents through profiling, memory allocation cuts, and CPU optimization in Go projects using a strict measurement-first cycle. Claude Code CX Codex Cursor +1 41,800installs golang-concurrency samber The skill sets rules for concurrent Go code: goroutine lifecycle, channels and select, mutexes, errgroup, singleflight, worker pools, and fan-out/fan-in pipelines. Claude Code CX Codex Cursor +1 41,600installs golang-database samber Go database guidelines for database/sql, sqlx, and pgx. Enforces parameterized queries, context passing, and explicit connection pool handling without ORMs. Claude Code CX Codex Cursor +1 40,700installs golang-naming samber A Go naming skill for writing, reviewing, and refactoring code. It covers packages, types, errors, booleans, enums, and tests. Claude Code CX Codex Cursor +1 40,700installs

Similar

stakeholder-update official anthropics This skill drafts project updates for a chosen audience and cadence, from leadership summaries to customer announcements. Use it for recurring status reports, launches, or escalations. Claude Code CX Codex Cursor +1 2,900installs discover-brand official anthropics Finds brand assets across connected enterprise platforms and builds a structured discovery report. It helps audit style guides and brand voice materials without manual searching. Claude Code CX Codex Cursor +1 2,900installs guideline-generation official anthropics Builds brand voice guidelines and tone matrices from source documents, transcripts, and discovery reports. Useful for codifying brand rules into LLM-ready markdown files. Claude Code CX Codex Cursor +1 2,900installs adev-writing-guide angular Guidelines for writing Angular documentation in adev/src/content. It enforces Google Technical Writing standards, Angular markdown extensions, and custom code components. Claude Code CX Codex Cursor +1 912installs firecrawl-download firecrawl Downloads an entire website or specific sections into local markdown files and screenshots. Useful for keeping offline docs ready for an agent. Claude Code CX Codex Cursor +1 79,800installs newsletter-generation bytedance Generates professional email digests and newsletters with topic research via web search, multi-source curation, and ready-to-publish markdown output. Claude Code CX Codex Cursor +1 1,800installs grill-with-docs Matt Pocock This skill interviews you about a plan or design and creates ADRs and a glossary along the way. Use it when decisions need sharper definition. Claude Code 1,219,756installs skill-creator official anthropics Creates and refines skills, then tests them with prompts, evaluations, and performance checks. Claude Code Claude.ai 414,180installs

Questions about golang-swagger

How do I install golang-swagger in Claude Code?

Run npx skills add samber/cc-skills-golang --skill golang-swagger -a claude-code, then open ~/.claude/skills/golang-swagger/SKILL.md.

What does golang-swagger do?

It guides the agent through documenting Go APIs with swaggo/swag, adding handler annotations, generating OpenAPI files, and wiring Swagger UI.

What does golang-swagger require?

The environment needs go and the swag CLI. Documentation generation uses swag init or swag init -g cmd/api/main.go.

Source text

SKILL.md · MIT
---
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, Codex or similar harness. Requires go and swag CLI.
metadata:
  author: samber
  version: "1.1.2"
  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 Bash(godig:*) Bash(gopls:*) LSP mcp__gopls__*
paths:
  - "**/*.go"
---

**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   [email protected]
// @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:

- For Go package docs, symbols, versions, importers, and known vulnerabilities, → See `samber/cc-skills-golang@golang-pkg-go-dev` skill (`godig`), preferred 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 <https://github.com/swaggo/swag/issues>.

© samber · MIT · samber/cc-skills-golang

See also

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor