gofiber/swagger

repository·main·Indexed 19 days ago

https://github.com/gofiber/swagger

Deprecated Swagger middleware for the Fiber web framework. Provides functionality to serve Swagger UI and generated documentation JSON via the New() function and HandlerDefault. Users are advised to migrate to the maintained version at github.com/gofiber/contrib/v3/swaggo.

Tokens
2.8K
Snippets
7
Records
10
Agent score
67%

What's inside gofiber-swagger

  1. Migrate from the deprecated Swagger middleware

    main

    The gofiber/swagger repository is deprecated and no longer maintained. To continue using Swagger with Fiber, migrate to the maintained version located in the Fiber Contrib repository.

    New Package: github.com/gofiber/contrib/v3/swaggo

  2. Configure Request and Response Interceptors

    main

    Swagger UI allows you to intercept remote definitions, "Try it out" requests, and OAuth 2.0 requests/responses using JavaScript functions provided via template.JS.

    • RequestInterceptor: A function that accepts one argument requestInterceptor(request) and must return the modified request (or a Promise resolving to it).
    • ResponseInterceptor: A function that accepts one argument responseInterceptor(response) and must return the modified response (or a Promise resolving to it).
    • ShowMutatedRequest: If true, the UI will use the mutated request returned from the RequestInterceptor to generate the displayed curl command.
  3. Configure Swagger UI via the Config struct

    main

    The Config struct is used to customize the behavior and appearance of the Swagger UI middleware. It allows you to control API definition URLs, UI layout, syntax highlighting, OAuth2 settings, and request/response interception.

    When initializing your configuration, it is recommended to use the configDefault helper function to ensure that all fields not explicitly set are populated with their intended default values. This prevents breaking the UI by omitting required internal defaults like Plugins or Presets.

    import "github.com/gofiber/swagger"
    
    // Example of creating a custom configuration
    cfg := swagger.ConfigDefault
    cfg.Title = "My Custom API"
    cfg.URL = "/api-docs/swagger.json"
    cfg.TryItOutEnabled = true
    // Use the helper to ensure all other defaults are applied correctly
    finalCfg := swagger.ConfigDefault(cfg)
  4. Configure Syntax Highlighting

    main

    You can control the syntax highlighting behavior using the SyntaxHighlight field in the Config struct, which takes a *SyntaxHighlightConfig object.

    Supported themes for Highlight.js include:

    • agate (default)
    • arta
    • monokai
    • nord
    • obsidian
    • tomorrow-night
    SyntaxHighlight: &swagger.SyntaxHighlightConfig{
        Activate: true,
        Theme: "monokai",
    }
  5. Configure OAuth2 settings

    main

    To enable OAuth2 authentication in Swagger UI, provide an OAuthConfig object to the OAuth field in your Config.

    Note: ClientSecret should never be used in production environments as it exposes sensitive information. It is intended for development and testing only.

    OAuth: &swagger.OAuthConfig{
        ClientId: "your-client-id",
        AppName:  "Your App Name",
        Scopes:   []string{"read", "write"},
    }
  6. Configure the Swagger middleware

    main

    The New function accepts optional Config arguments to customize the Swagger middleware. While the full struct definition is not in this file, the middleware utilizes the following logic:

    • URL: If cfg.URL is empty, the middleware defaults to doc.json relative to the current prefix.
    • InstanceName: Used to retrieve the documentation via swag.ReadDoc(cfg.InstanceName). This must match the instance name used when generating your Swagger documentation.

    Note: The middleware automatically handles X-Forwarded-Prefix headers to correctly resolve paths when running behind a proxy.

  7. Configure Filtering

    main

    The Filter field allows you to enable a search box in the Swagger UI top bar to filter tagged operations. It uses a FilterConfig struct.

    • Enabled: A boolean to turn filtering on or off.
    • Expression: A string used as the initial filter expression. Filtering is case-sensitive and matches the expression anywhere inside the tag.
    Filter: swagger.FilterConfig{
        Enabled:    true,
        Expression: "user",
    }
  8. Initialize Swagger middleware with New()

    main

    The New function returns a fiber.Handler that serves the Swagger UI and the generated documentation JSON. You can use it without arguments to get a default handler, or pass a Config object to customize the behavior.

    By default, the middleware serves index.html and doc.json. It also supports serving static assets from the Swagger filesystem.

    If no configuration is provided, it uses HandlerDefault which is a pre-initialized instance of the middleware.

    import (
    	"github.com/gofiber/fiber/v3"
    	"github.com/gofiber/gofiber/swagger"
    )
    
    func main() {
    
    app := fiber.New()
    
    // Use the default handler
    app.Use("/swagger/*", swagger.HandlerDefault)
    
    // Or create a custom handler with configuration
    // app.Use("/swagger/*", swagger.New(swagger.Config{ ... }))
    
    app.Listen(":3000")
    }
  9. Reference: Config struct fields

    main

    The following fields are available in the Config struct to customize the Swagger UI instance:

    // URL to fetch external configuration document from.
    // default: ""
    ConfigURL string `json:"configUrl,omitempty"`
    
    // The URL pointing to API definition (normally swagger.json or swagger.yaml).
    // default: "doc.json"
    URL string `json:"url,omitempty"`
    
    // Enables overriding configuration parameters via URL search params.
    // default: false
    QueryConfigEnabled bool `json:"queryConfigEnabled,omitempty"`
    
    // The name of a component available via the plugin system to use as the top-level layout for Swagger UI.
    // default: "StandaloneLayout"
    Layout string `json:"layout,omitempty"`
    
    // Enables deep linking for tags and operations.
    // default: true
    DeepLinking bool `json:"deepLinking"`
    
    // Controls the display of operationId in operations list.
    // default: false
    DisplayOperationId bool `json:"displayOperationId,omitempty"`
    
    // The default expansion depth for models (set to -1 completely hide the models).
    // default: 1
    DefaultModelsExpandDepth int `json:"defaultModelsExpandDepth,omitempty"`
    
    // Controls how the model is shown when the API is first rendered.
    // default: "example"
    DefaultModelRendering string `json:"defaultModelRendering,omitempty"`
    
    // Controls the display of the request duration (in milliseconds) for "Try it out" requests.
    // default: false
    DisplayRequestDuration bool `json:"displayRequestDuration,omitempty"`
    
    // Controls the default expansion setting for the operations and tags.
    // 'list' (default, expands only the tags),
    // 'full' (expands the tags and operations),
    // 'none' (expands nothing)
    DocExpansion string `json:"docExpansion,omitempty"`
    
    // If set, enables filtering. The top bar will show an edit box that you can use to filter the tagged operations that are shown.
    // default: false
    Filter FilterConfig `json:"-"`
    
    // Controls the display of vendor extension (x-) fields and values for Operations, Parameters, Responses, and Schema.
    // default: false
    ShowExtensions bool `json:"showExtensions,omitempty"`
    
    // Controls the display of the "Try it out" section should be enabled by default.
    // default: false
    TryItOutEnabled bool `json:"tryItOutEnabled,omitempty"`
    
    // List of HTTP methods that have the "Try it out" feature enabled.
    // default: nil
    SupportedSubmitMethods []string `json:"supportedSubmitMethods,omitempty"`
    
    // If set to true, enables passing credentials, as defined in the Fetch standard, in CORS requests.
    // default: false
    WithCredentials bool `json:"withCredentials,omitempty"`
    
    // If set to true, it persists authorization data and it would not be lost on browser close/refresh.
    // default: false
    PersistAuthorization bool `json:"persistAuthorization,omitempty"`
  10. Use HandlerDefault for quick setup

    main

    For most standard use cases, you can use the exported HandlerDefault variable. This is a pre-configured instance of the Swagger middleware that requires no additional setup beyond being mounted to a route in your Fiber application.

    app.Use("/swagger/*", swagger.HandlerDefault)