Generated banner for Golang Swagger
Generated logo for Golang Swagger

Golang Swagger

Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe

  • Skill
  • Tool integration
  • Software development
  • MIT
  • No issues found

From the author

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.
— the description by samber

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The golang-swagger skill provides a comprehensive approach to documenting Go APIs by leveraging the swaggo/swag toolchain. It enables developers to define API specifications directly within their source code using annotation comments and struct tags. The skill covers the entire lifecycle of API documentation, including tool installation, annotation patterns for handlers and models, framework-specific UI integration, and the generation of Swagger/OpenAPI specifications. It ensures that documentation remains a reliable contract for API consumers by keeping the spec synchronized with the implementation.

What it does

  • Generates Swagger/OpenAPI documentation from Go source code annotations.
  • Supports major Go web frameworks including Gin, Echo, Fiber, Chi, and net/http.
  • Enables definition of security schemes like Bearer/JWT, OAuth2, and API keys.
  • Provides struct tags for fine-grained control over schema generation and field exclusion.
  • Supports advanced features like generics and nested composition in API responses.
  • Includes formatting tools to maintain consistent annotation style across the codebase.

When to use it

  • When you need to generate and maintain OpenAPI documentation for a Go-based REST API.
  • When you want to keep API documentation and implementation in sync within the same codebase.
  • When you need to expose a Swagger UI endpoint for API testing and discovery.
  • When you need to define complex API schemas, security requirements, or response structures.

Advantages

  • Reduces documentation drift by keeping specs close to the code.
  • Simplifies the creation of interactive API documentation (Swagger UI).
  • Provides a standardized way to define security and parameter requirements.
  • Supports common Go web frameworks with minimal boilerplate.
  • Allows for runtime configuration of API metadata like host and base path.

Usage examples

“Add Swagger documentation to my existing Gin API.”
The agent will install the swag CLI, guide you through adding the necessary annotations to your handler functions, and help you wire the gin-swagger handler to your router.
“How do I document a protected endpoint that requires a Bearer token?”
The agent will show you how to define the security definition in your main.go and apply the @Security Bearer annotation to your specific handler function.
“Generate the Swagger documentation files for my project.”
The agent will execute the swag init command to parse your source code and generate the required docs/ directory containing the OpenAPI specification.
“How can I exclude a sensitive field from my API documentation?”
The agent will instruct you to add the `swaggerignore:"true"` struct tag to the specific field in your Go model.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/samber/golang-swagger/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip golang-swagger.zip -d .agents/skills

Documentation by samber

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:

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:

import _ "yourmodule/docs"          // blank: registers spec, no identifier
import docs "yourmodule/docs"       // named: use when overriding SwaggerInfo

Wire the UI endpoint — pick your framework:

// 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:

import docs "yourmodule/docs"

docs.SwaggerInfo.Host     = os.Getenv("API_HOST")
docs.SwaggerInfo.BasePath = "/api/v1"

Full CLI reference

General API Info

Place in main.go (or the file passed via -g). These annotations define the top-level spec:

// @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.

// 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
pathURL path segment (/users/{id})
queryURL query string (?filter=x)
bodyRequest body — type must be a struct
headerHTTP header
formDataMultipart/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 / integerPrimitive

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.

// 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:

// @Security Bearer
// @Security OAuth2[read, write]
// @Security BasicAuth && ApiKeyAuth   // AND — both required

Struct Tags

Enrich models without changing their Go type:

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
}
TagPurpose
exampleExample value shown in Swagger UI
enumsComma-separated allowed values
swaggertypeOverride detected type (e.g., "primitive,integer" for time.Time)
swaggerignore:"true"Exclude field from the generated schema
extensionsAdd OpenAPI extensions: extensions:"x-nullable,x-deprecated=true"

Common Mistakes

MistakeWhy it breaksFix
Missing _ "yourmodule/docs" importSchema not registered; UI loads emptyAdd blank import in main.go or server init
Stale docs/ after code changesDocs diverge from implementation; consumers get wrong schemaRe-run swag init after every annotation change
@Param body with primitive typeswag cannot derive schema from string; generation failsAlways use a named struct for body params
No @Security on protected routesSwagger UI shows no lock icon; testers send unauthenticated requestsApply @Security to every authenticated endpoint
General info annotations in the wrong fileswag silently skips them; spec has no title/hostUse -g <file> flag or move annotations to main.go
Using {object} with a map typeswag cannot generate a schema for map[string]any without helpUse a named struct or annotate with swaggertype
Multi-word @Tags without quotesTags split on spaces, producing malformed groupingQuote 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.

Files

references/swag-cli.md

swag CLI Reference

Table of Contents

  • swag init — Generate Documentation

  • swag fmt — Format Annotations

  • Framework Integration Packages

  • Dynamic Configuration

  • Generics (swag v2)

  • Nested Composition

  • Response Headers

  • Function-Scoped Structs

  • MIME Type Aliases

swag init — Generate Documentation

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

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

FrameworkPackage
Gingithub.com/swaggo/gin-swagger
Echogithub.com/swaggo/echo-swagger
Fibergithub.com/swaggo/fiber-swagger
Chi / net/http / Gorillagithub.com/swaggo/http-swagger
Buffalogithub.com/swaggo/buffalo-swagger
Hertzgithub.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:

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:

// @Success 200 {object} api.Response[model.User]
// @Success 200 {array}  api.Response[model.User]

Multiple type parameters:

// @Success 200 {object} api.Response[model.User, model.Meta]

Nested Composition

Embed or override fields in the documented schema without changing Go types:

// @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

// @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:

// @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

AliasContent-Type
jsonapplication/json
xmlapplication/xml
plaintext/plain
htmltext/html
mpfdmultipart/form-data
x-www-form-urlencodedapplication/x-www-form-urlencoded
octet-streamapplication/octet-stream
png / jpeg / gifimage/png, image/jpeg, image/gif
event-streamtext/event-stream

Requirements and compatibility

Written for: Claude Code, OpenAI Codex

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools, Claude Code frontmatter, Needs an API key

The author says: Designed for Claude Code, Codex or similar harness. Requires go and swag CLI.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
samber
Publisher
Samuel Berthe (Community)
Distributed by
Samuel Berthe
Source
samber/cc-skills-golang · skills/golang-swagger · commit bb1d43d
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-swagger.zip