### Install Hertz-Swagger and Files Source: https://github.com/hertz-contrib/swagger/blob/main/README.md Download the hertz-swagger middleware and the swaggo/files package using go get. ```sh go get -u github.com/hertz-contrib/swagger go get -u github.com/swaggo/files ``` -------------------------------- ### Install Swag CLI Source: https://github.com/hertz-contrib/swagger/blob/main/README.md Install the Swag command-line interface tool for generating Swagger documentation. Use 'go install' for Go 1.17 and later. ```sh go get -u github.com/swaggo/swag/cmd/swag ``` ```sh go install github.com/swaggo/swag/cmd/swag@latest ``` -------------------------------- ### Hertz Application with Swagger UI Source: https://github.com/hertz-contrib/swagger/blob/main/README.md This is a full example of a Hertz application integrating hertz-swagger. It defines a handler, configures Swagger UI, and starts the server. Ensure the 'docs' import path matches your project structure. ```go package main import ( "context" "github.com/cloudwego/hertz/pkg/app" "github.com/cloudwego/hertz/pkg/app/server" "github.com/hertz-contrib/swagger" _ "github.com/hertz-contrib/swagger/example/basic/docs" sswaggerFiles "github.com/swaggo/files" ) // PingHandler 测试handler // @Summary 测试Summary // @Description 测试Description // @Accept application/json // @Produce application/json // @Router /ping [get] func PingHandler(c context.Context, ctx *app.RequestContext) { ctx.JSON(200, map[string]string{ "ping": "pong", }) } // @title HertzTest // @version 1.0 // @description This is a demo using Hertz. // @contact.name hertz-contrib // @contact.url https://github.com/hertz-contrib // @license.name Apache 2.0 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @host localhost:8888 // @BasePath / // @schemes http func main() { h := server.Default() h.GET("/ping", PingHandler) url := swagger.URL("http://localhost:8888/swagger/doc.json") // The url pointing to API definition h.GET("/swagger/*any", swagger.WrapHandler(swaggerFiles.Handler, url)) h.Spin() } ``` -------------------------------- ### Document Handlers with Swagger Annotation Comments Source: https://context7.com/hertz-contrib/swagger/llms.txt Use structured Go comments starting with `// @` to annotate handler functions and the `main` package. The `swag init` command parses these comments to generate API documentation files like `docs/docs.go`, `docs/swagger.json`, and `docs/swagger.yaml`. ```go // @title Bookstore API // @version 2.0 // @description Manages books and authors. // @contact.name API Support // @contact.url https://example.com/support // @license.name Apache 2.0 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @host localhost:8888 // @BasePath /api/v1 // @schemes http https func main() { h := server.Default() // ... register routes ... h.Spin() } // GetBook godoc // @Summary Get a book by ID // @Description Returns a single book record // @Tags books // @Accept application/json // @Produce application/json // @Param id path int true "Book ID" // @Success 200 {object} Book // @Failure 404 {object} map[string]string // @Router /books/{id} [get] func GetBook(c context.Context, ctx *app.RequestContext) { id := ctx.Param("id") // fetch book by id ... ctx.JSON(200, Book{ID: 1, Title: "Go Programming"}) } type Book struct { ID int `json:"id"` Title string `json:"title"` } ``` -------------------------------- ### Run Swag Init Source: https://github.com/hertz-contrib/swagger/blob/main/README.md Execute the 'swag init' command in your Go project's root directory to parse comments and generate documentation files (e.g., 'docs' folder and 'docs/doc.go'). ```sh swag init ``` -------------------------------- ### Import Generated Docs Source: https://github.com/hertz-contrib/swagger/blob/main/README.md Import the generated Swagger documentation package. Replace 'github.com/go-project-name/docs' with your project's actual import path for the docs. ```go import ( docs "github.com/go-project-name/docs" ) ``` -------------------------------- ### Import Hertz-Swagger and Files Source: https://github.com/hertz-contrib/swagger/blob/main/README.md Import the necessary packages for hertz-swagger middleware and swagger embed files in your Go code. ```go import "github.com/hertz-contrib/swagger" // hertz-swagger middleware import "github.com/swaggo/files" // swagger embed files ``` -------------------------------- ### Support Multiple Swagger Instances on One Router Source: https://context7.com/hertz-contrib/swagger/llms.txt Use `InstanceName` to select which registered `swag` document instance to serve. This is useful when deploying multiple independent Swagger specs on a single Hertz server. Ensure you also use the `--instanceName` flag with `swag init` during documentation generation. ```go // Generate docs for two separate API groups: // swag init --instanceName public --output docs/public // swag init --instanceName internal --output docs/internal import ( _ "github.com/myorg/myapp/docs/public" _ "github.com/myorg/myapp/docs/internal" ) // Serve public API docs h.GET("/swagger/public/*any", swagger.WrapHandler( swaggerFiles.Handler, swagger.InstanceName("public"), swagger.URL("http://localhost:8888/swagger/public/doc.json"), )) // Serve internal API docs h.GET("/swagger/internal/*any", swagger.WrapHandler( swaggerFiles.Handler, swagger.InstanceName("internal"), swagger.URL("http://localhost:8888/swagger/internal/doc.json"), )) ``` -------------------------------- ### Register Swagger UI with WrapHandler Source: https://context7.com/hertz-contrib/swagger/llms.txt Mounts the Swagger UI onto a Hertz router using `WrapHandler` with functional options for configuration. Ensure the `docs` package is generated by `swag init` and imported. ```go package main import ( "context" "github.com/cloudwego/hertz/pkg/app" "github.com/cloudwego/hertz/pkg/app/server" "github.com/hertz-contrib/swagger" _ "github.com/myorg/myapp/docs" // generated by swag init swaggerFiles "github.com/swaggo/files" ) // @title My API // @version 1.0 // @description A sample Hertz application. // @host localhost:8888 // @BasePath / func main() { h := server.Default() h.GET("/api/ping", PingHandler) // Mount Swagger UI at /swagger/*any // URL() points the UI at the JSON spec endpoint h.GET("/swagger/*any", swagger.WrapHandler( swaggerFiles.Handler, swagger.URL("http://localhost:8888/swagger/doc.json"), swagger.DocExpansion("list"), swagger.DeepLinking(true), swagger.DefaultModelsExpandDepth(1), swagger.PersistAuthorization(false), )) h.Spin() // Visit http://localhost:8888/swagger/index.html } func PingHandler(c context.Context, ctx *app.RequestContext) { ctx.JSON(200, map[string]string{"ping": "pong"}) } ``` -------------------------------- ### Control Default Expansion with swagger.DocExpansion Source: https://context7.com/hertz-contrib/swagger/llms.txt Sets how operations and tags are expanded on initial load using the `DocExpansion` functional option. Accepted values are `"list"` (tags only, default), `"full"` (tags + operations), and `"none"` (collapsed). ```go h.GET("/swagger/*any", swagger.WrapHandler( swaggerFiles.Handler, swagger.URL("http://localhost:8888/swagger/doc.json"), swagger.DocExpansion("full"), // expand all operations on load )) ``` -------------------------------- ### InstanceName Source: https://context7.com/hertz-contrib/swagger/llms.txt Allows serving multiple independent Swagger instances on a single Hertz server by selecting a registered 'swag' document instance. ```APIDOC ## InstanceName ### Description Selects which registered `swag` document instance to serve. Useful for deploying multiple Swagger specs on one server. ### Method `swagger.InstanceName(name string)` ### Parameters - **name** (string) - The name of the Swagger instance to serve. ``` -------------------------------- ### SyntaxHighlight Source: https://context7.com/hertz-contrib/swagger/llms.txt Toggles syntax highlighting in the response body panel of the Swagger UI. Can be disabled for performance with large payloads. ```APIDOC ## SyntaxHighlight ### Description Enables or disables syntax highlighting in the Swagger UI response body panel. Can be turned off for performance. ### Method `swagger.SyntaxHighlight(enabled bool)` ### Parameters - **enabled** (bool) - Whether to enable syntax highlighting. Defaults to true. ``` -------------------------------- ### Register Swagger UI with CustomWrapHandler and Config Source: https://context7.com/hertz-contrib/swagger/llms.txt Mounts the Swagger UI using `CustomWrapHandler` with a pre-configured `Config` struct. This provides direct control over all settings and is useful for programmatic configuration. ```go package main import ( "os" "github.com/cloudwego/hertz/pkg/app/server" "github.com/hertz-contrib/swagger" _ "github.com/myorg/myapp/docs" swaggerFiles "github.com/swaggo/files" "github.com/swaggo/swag" ) func main() { h := server.Default() cfg := &swagger.Config{ URL: "http://localhost:8888/swagger/doc.json", DocExpansion: "full", InstanceName: swag.Name, // "swagger" Title: "My API Docs", DefaultModelsExpandDepth: -1, // hide models section DeepLinking: true, PersistAuthorization: true, Oauth2DefaultClientID: os.Getenv("OAUTH_CLIENT_ID"), SyntaxHighlight: true, } h.GET("/swagger/*any", swagger.CustomWrapHandler(cfg, swaggerFiles.Handler)) h.Spin() } ``` -------------------------------- ### Swagger Annotation Comments Source: https://context7.com/hertz-contrib/swagger/llms.txt Document API handlers using structured Go comments that the `swag init` tool parses to generate Swagger documentation files. ```APIDOC ## Swagger Annotation Comments ### Description Use structured Go comments (e.g., `@title`, `@version`, `@description`, `@param`, `@success`, `@router`) to document handlers and generate Swagger specifications. ### Example Usage ```go // @title Bookstore API // @version 2.0 // @description Manages books and authors. // @host localhost:8888 // @BasePath /api/v1 func main() { h := server.Default() // ... register routes ... h.Spin() } // GetBook godoc // @Summary Get a book by ID // @Description Returns a single book record // @Tags books // @Accept application/json // @Produce application/json // @Param id path int true "Book ID" // @Success 200 {object} Book // @Failure 404 {object} map[string]string // @Router /books/{id} [get] func GetBook(c context.Context, ctx *app.RequestContext) { // ... implementation ... } type Book struct { ID int `json:"id"` Title string `json:"title"` } ``` ``` -------------------------------- ### Toggle Response Body Syntax Highlighting Source: https://context7.com/hertz-contrib/swagger/llms.txt The `SyntaxHighlight` option enables or disables syntax highlighting in the response body panel. Disabling it can improve rendering performance for large payloads. ```go h.GET("/swagger/*any", swagger.WrapHandler( swaggerFiles.Handler, swagger.SyntaxHighlight(true), )) ``` -------------------------------- ### Enable Deep Linking with swagger.DeepLinking Source: https://context7.com/hertz-contrib/swagger/llms.txt Enables or disables Swagger UI deep linking using the `DeepLinking` functional option. When enabled, the browser URL reflects the currently expanded operation, allowing bookmarking and sharing. ```go h.GET("/swagger/*any", swagger.WrapHandler( swaggerFiles.Handler, swagger.DeepLinking(true), )) ``` -------------------------------- ### Set API Definition URL with swagger.URL Source: https://context7.com/hertz-contrib/swagger/llms.txt Configures the Swagger UI to load the OpenAPI JSON spec from a specified absolute URL using the `URL` functional option. Defaults to `doc.json` relative to the mounted path. ```go // Absolute URL to an externally hosted spec urlOpt := swagger.URL("https://api.example.com/openapi/doc.json") h.GET("/swagger/*any", swagger.WrapHandler(swaggerFiles.Handler, urlOpt)) ``` -------------------------------- ### Add API Comments for Swagger Source: https://github.com/hertz-contrib/swagger/blob/main/README.md Add declarative comments to your Go handler functions to define API metadata for Swagger documentation. Ensure the 'Router' tag matches your Hertz route. ```go // PingHandler 测试handler // @Summary 测试Summary // @Description 测试Description // @Accept application/json // @Produce application/json // @Router /ping [get] func PingHandler(c context.Context, ctx *app.RequestContext) { ctx.JSON(200, map[string]string{ "ping": "pong", }) } ``` -------------------------------- ### WrapHandler - Register Swagger UI with functional options Source: https://context7.com/hertz-contrib/swagger/llms.txt The `WrapHandler` function wraps `swaggerFiles.Handler` into a Hertz `app.HandlerFunc`. It applies default configuration values and accepts functional options to customize the Swagger UI behavior. This is the primary method for mounting the Swagger UI onto a Hertz router. ```APIDOC ## WrapHandler - Register Swagger UI with functional options ### Description The `WrapHandler` function wraps `swaggerFiles.Handler` (a `*webdav.Handler`) into a Hertz `app.HandlerFunc`, applying default configuration values and any number of option functions. It is the primary entry point for mounting the Swagger UI onto a Hertz router. ### Method GET ### Endpoint /swagger/*any ### Parameters #### Query Parameters - **URL** (string) - Optional - Specifies the URL for the OpenAPI JSON spec. Defaults to `"doc.json"`. - **DocExpansion** (string) - Optional - Controls default operation/tag expansion. Accepted values: `"list"` (tags only, default), `"full"` (tags + operations), `"none"` (collapsed). - **DeepLinking** (boolean) - Optional - Enables or disables Swagger UI deep linking. Defaults to `true`. ### Request Example ```go package main import ( "context" "github.com/cloudwego/hertz/pkg/app" "github.com/cloudwego/hertz/pkg/app/server" "github.com/hertz-contrib/swagger" _ "github.com/myorg/myapp/docs" // generated by swag init swaggerFiles "github.com/swaggo/files" ) // @title My API // @version 1.0 // @description A sample Hertz application. // @host localhost:8888 // @BasePath / func main() { h := server.Default() h.GET("/api/ping", PingHandler) // Mount Swagger UI at /swagger/*any // URL() points the UI at the JSON spec endpoint h.GET("/swagger/*any", swagger.WrapHandler( swaggerFiles.Handler, swagger.URL("http://localhost:8888/swagger/doc.json"), swagger.DocExpansion("list"), swagger.DeepLinking(true), swagger.DefaultModelsExpandDepth(1), swagger.PersistAuthorization(false), )) h.Spin() // Visit http://localhost:8888/swagger/index.html } func PingHandler(c context.Context, ctx *app.RequestContext) { ctx.JSON(200, map[string]string{"ping": "pong"}) } ``` ### Response #### Success Response (200) Serves the Swagger UI bundle (HTML, CSS, JS, JSON spec). ``` -------------------------------- ### CustomWrapHandler - Register Swagger UI with an explicit Config struct Source: https://context7.com/hertz-contrib/swagger/llms.txt The `CustomWrapHandler` function allows for direct struct-level control over all Swagger UI settings by accepting a fully populated `*Config` value. This is useful when configuration needs to be assembled programmatically. ```APIDOC ## CustomWrapHandler - Register Swagger UI with an explicit Config struct ### Description `CustomWrapHandler` accepts a fully populated `*Config` value instead of variadic option functions, giving direct struct-level control over all settings. Useful when configuration is assembled programmatically (e.g., from environment variables). ### Method GET ### Endpoint /swagger/*any ### Parameters #### Request Body - **Config** (*swagger.Config) - Required - A struct containing all configuration options for the Swagger UI. - **URL** (string) - The URL for the OpenAPI JSON spec. - **DocExpansion** (string) - Controls default operation/tag expansion. Accepted values: `"list"`, `"full"`, `"none"`. - **InstanceName** (string) - The name of the Swagger UI instance. - **Title** (string) - The title displayed in the Swagger UI. - **DefaultModelsExpandDepth** (int) - The default depth for expanding models. `-1` hides the models section. - **DeepLinking** (boolean) - Enables or disables Swagger UI deep linking. - **PersistAuthorization** (boolean) - Persists authorization information across sessions. - **Oauth2DefaultClientID** (string) - The default client ID for OAuth2 authentication. - **SyntaxHighlight** (boolean) - Enables syntax highlighting for code examples. ### Request Example ```go package main import ( "os" "github.com/cloudwego/hertz/pkg/app/server" "github.com/hertz-contrib/swagger" _ "github.com/myorg/myapp/docs" swaggerFiles "github.com/swaggo/files" "github.com/swaggo/swag" ) func main() { h := server.Default() cfg := &swagger.Config{ URL: "http://localhost:8888/swagger/doc.json", DocExpansion: "full", InstanceName: swag.Name, // "swagger" Title: "My API Docs", DefaultModelsExpandDepth: -1, // hide models section DeepLinking: true, PersistAuthorization: true, Oauth2DefaultClientID: os.Getenv("OAUTH_CLIENT_ID"), SyntaxHighlight: true, } h.GET("/swagger/*any", swagger.CustomWrapHandler(cfg, swaggerFiles.Handler)) h.Spin() } ``` ### Response #### Success Response (200) Serves the Swagger UI bundle (HTML, CSS, JS, JSON spec). ``` -------------------------------- ### Persist OAuth2/JWT Tokens Across Page Reloads Source: https://context7.com/hertz-contrib/swagger/llms.txt Set `PersistAuthorization` to `true` to save authorization data in browser local storage, preventing loss on page refresh. Defaults to `false`. ```go h.GET("/swagger/*any", swagger.WrapHandler( swaggerFiles.Handler, swagger.PersistAuthorization(true), )) ``` -------------------------------- ### Pre-populate OAuth2 Client ID Field Source: https://context7.com/hertz-contrib/swagger/llms.txt Use `Oauth2DefaultClientID` to pre-fill the `client_id` field in the Swagger UI OAuth2 authorization dialog, simplifying testing by reducing manual input. ```go h.GET("/swagger/*any", swagger.WrapHandler( swaggerFiles.Handler, swagger.Oauth2DefaultClientID("my-swagger-client"), swagger.PersistAuthorization(true), )) ``` -------------------------------- ### PersistAuthorization Source: https://context7.com/hertz-contrib/swagger/llms.txt Persists OAuth2/JWT tokens across page reloads by saving them in browser local storage. Defaults to false. ```APIDOC ## PersistAuthorization ### Description Persists authorization data (OAuth2/JWT tokens) in browser local storage, preventing loss on page refresh. ### Method `swagger.PersistAuthorization(persist bool)` ### Parameters - **persist** (bool) - Whether to persist authorization data. Defaults to false. ``` -------------------------------- ### Set Default Models Expand Depth for Swagger UI Source: https://context7.com/hertz-contrib/swagger/llms.txt Use `DefaultModelsExpandDepth` to control how deeply response/request models are expanded by default. Pass -1 to hide the models section entirely. ```go h.GET("/swagger/*any", swagger.WrapHandler( swaggerFiles.Handler, swagger.DefaultModelsExpandDepth(-1), // hide all models )) ``` -------------------------------- ### DefaultModelsExpandDepth Source: https://context7.com/hertz-contrib/swagger/llms.txt Controls the default expansion depth for request and response models in the Swagger UI. Setting it to -1 hides the models section entirely. ```APIDOC ## DefaultModelsExpandDepth ### Description Sets the default expansion depth for response/request models in the Swagger UI. Use -1 to hide the models section. ### Method `swagger.DefaultModelsExpandDepth(depth int)` ### Parameters - **depth** (int) - The expansion depth. -1 to hide models. ``` -------------------------------- ### Functional Options Source: https://context7.com/hertz-contrib/swagger/llms.txt Hertz Swagger provides several functional options to customize the Swagger UI behavior when using `WrapHandler`. These options allow fine-grained control over aspects like the API definition URL, expansion states, and deep linking. ```APIDOC ## Functional Options ### URL — Set the API definition URL `URL` returns a functional option that overrides the path or URL the Swagger UI uses to load the OpenAPI JSON spec. Defaults to `"doc.json"` (relative to the mounted path). ```go // Absolute URL to an externally hosted spec urlOpt := swagger.URL("https://api.example.com/openapi/doc.json") h.GET("/swagger/*any", swagger.WrapHandler(swaggerFiles.Handler, urlOpt)) ``` ### DocExpansion — Control default operation/tag expansion `DocExpansion` returns a functional option that sets how operations and tags are expanded on initial load. Accepted values: `"list"` (tags only, default), `"full"` (tags + operations), `"none"` (collapsed). ```go h.GET("/swagger/*any", swagger.WrapHandler( swaggerFiles.Handler, swagger.URL("http://localhost:8888/swagger/doc.json"), swagger.DocExpansion("full"), // expand all operations on load )) ``` ### DeepLinking — Enable deep linking for tags and operations `DeepLinking` returns a functional option that enables or disables Swagger UI deep linking, allowing the browser URL to reflect the currently expanded operation so it can be bookmarked or shared. Defaults to `true`. ```go h.GET("/swagger/*any", swagger.WrapHandler( swaggerFiles.Handler, swagger.DeepLinking(true), )) ``` ``` -------------------------------- ### Oauth2DefaultClientID Source: https://context7.com/hertz-contrib/swagger/llms.txt Pre-populates the client ID field in the Swagger UI OAuth2 authorization dialog for easier testing. ```APIDOC ## Oauth2DefaultClientID ### Description Pre-fills the `client_id` field in the Swagger UI OAuth2 authorization dialog. ### Method `swagger.Oauth2DefaultClientID(clientID string)` ### Parameters - **clientID** (string) - The default client ID to pre-populate. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.