golang-swagger

द्वारा samber

Golang OpenAPI/Swagger दस्तावेज़ीकरण swaggo/swag के साथ — एनोटेशन टिप्पणियाँ (@Summary, @Param, @Success, @Router, @Security), swag init कोड जनरेशन, फ्रेमवर्क एकीकरण (gin, echo, fiber, chi, net/http), सुरक्षा परिभाषाएँ (Bearer/JWT, OAuth2, API key), और स्ट्रक्ट टैग (swaggertype, enums, example, swaggerignore)। तब लागू करें जब किसी Go प्रोजेक्ट में Swagger/OpenAPI दस्तावेज़ जोड़े या बनाए रखे जा रहे हों, या जब कोडबेस github.com/swaggo/swag, github.com/swaggo/gin-swagger,... आयात करता हो।

npx skills add https://github.com/samber/cc-skills-golang --skill golang-swagger

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

samber की और Skills

golang-code-style
samber
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).
developmentcode-review
golang-testing
samber
प्रोडक्शन-रेडी गोलैंग टेस्ट — टेबल-ड्रिवन टेस्ट, टेस्टिफाई सूट और मॉक, पैरेलल टेस्ट, फज़िंग, फिक्स्चर, गोलिक के साथ गोरूटीन लीक डिटेक्शन, स्नैपशॉट टेस्टिंग, कोड कवरेज, इंटीग्रेशन टेस्ट, इडियोमैटिक टेस्ट नेमिंग। गो टेस्ट लिखते या रिव्यू करते समय, टेस्टिंग दृष्टिकोण चुनते समय, गो टेस्ट सीआई सेट अप करते समय, या फ्लैकी/स्लो टेस
developmenttestingcode-review
golang-design-patterns
samber
इडियोमैटिक गोलैंग डिज़ाइन पैटर्न — फंक्शनल ऑप्शंस, कंस्ट्रक्टर, एरर फ्लो और कैस्केडिंग, रिसोर्स मैनेजमेंट और लाइफसाइकिल, ग्रेसफुल शटडाउन, रेज़िलिएंस, आर्किटेक्चर, डिपेंडेंसी इंजेक्शन, डेटा हैंडलिंग, स्ट्रीमिंग और अन्य। तब लागू करें जब आर्किटेक्चरल पैटर्न के बीच स्पष्ट रूप से चुनाव करना हो, फंक्शनल ऑप्शंस लागू करना हो, कं
developmentdesigncode-review
golang-error-handling
samber
इडियोमैटिक गोलैंग एरर हैंडलिंग — %w के साथ क्रिएशन और रैपिंग, errors.Is/As, errors.Join, कस्टम एरर टाइप्स, सेंटिनल एरर्स, panic/recover, सिंगल हैंडलिंग रूल, slog के साथ स्ट्रक्चर्ड लॉगिंग, HTTP रिक्वेस्ट लॉगिंग मिडलवेयर, और प्रोडक्शन एरर्स के लिए samber/oops। लॉग एग्रीगेशन थर्ड-पार्टी टूल्स के साथ स्केल पर लॉग्स को उपयोगी बनाने के लिए बनाया गया। Go कोड में एरर्स बनाते, रैप करते, निर
developmentcode-review
golang-performance
samber
गोलांग प्रदर्शन अनुकूलन पैटर्न और पद्धति - यदि X अड़चन है, तो Y लागू करें। इसमें आवंटन कमी, CPU दक्षता, मेमोरी लेआउट, GC ट्यूनिंग, पूलिंग, कैशिंग और हॉट-पाथ अनुकूलन शामिल है। इसका उपयोग तब करें जब प्रोफाइलिंग या बेंचमार्क ने कोई अड़चन पहचान ली हो और आपको उसे ठीक करने के लिए सही अनुकूलन पैटर्न की आवश्यकता हो। इसका उपयोग प्रदर्शन कोड समीक्षा करते समय भी करें ताकि सुधार
developmentcode-review
golang-security
samber
गोलांग के लिए सुरक्षा सर्वोत्तम अभ्यास और भेद्यता रोकथाम। इंजेक्शन (SQL, कमांड, XSS), क्रिप्टोग्राफी, फाइलसिस्टम सुरक्षा, नेटवर्क सुरक्षा, कुकीज़, सीक्रेट्स प्रबंधन, मेमोरी सुरक्षा और लॉगिंग को शामिल करता है। सुरक्षा के लिए Go कोड लिखते, समीक्षा करते या ऑडिट करते समय, या क्रिप्टो, I/O, सीक्रेट्स प्रबंधन, उपयोगकर्ता इनपुट हैंडलिंग या प्रमाणीकरण से जुड़े किसी भी जोख
securitycode-reviewdevelopment
golang-database
samber
Go डेटाबेस एक्सेस के लिए व्यापक मार्गदर्शिका — पैरामीटराइज़्ड क्वेरीज़, स्ट्रक्ट स्कैनिंग, NULL योग्य कॉलम, ट्रांज़ैक्शन, आइसोलेशन लेवल, SELECT FOR UPDATE, कनेक्शन पूल, बैच प्रोसेसिंग, कॉन्टेक्स्ट प्रोपेगेशन और माइग्रेशन टूलिंग। PostgreSQL, MariaDB, MySQL या SQLite के साथ इंटरैक्ट करने वाले Golang कोड को लिखते, समीक्षा करते या डीबग करते समय उपयोग करें; डेटाबेस परीक्षण के लिए; या database/sql, sqlx या pg
developmentdatabase
golang-lint
samber
Golang प्रोजेक्ट्स के लिए लिंटिंग सर्वोत्तम अभ्यास और golangci-lint कॉन्फ़िगरेशन — लिंटर चलाना, .golangci.yml कॉन्फ़िगर करना, nolint निर्देशों के साथ चेतावनियाँ दबाना, लिंट आउटपुट की व्याख्या करना और लिंटर चुनना। इसका उपयोग तब करें जब golangci-lint कॉन्फ़िगर करना हो, लिंट चेतावनियों या nolint सप्रेशन के बारे में पूछना हो, कोड गुणवत्ता टूलिंग सेट अप करनी हो, या लिंटर चुनने हों। इसका उपयोग तब भी करें
developmentcode-reviewtesting