scalargo

package module
v0.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2025 License: MIT Imports: 9 Imported by: 3

README

🚀 Scalar-Go

Go Reference Go Report Card

🎯 Transform your OpenAPI specs into beautiful, interactive documentation with just a few lines of Go code!

Scalar-Go is the official Go integration for the powerful Scalar API Documentation platform. Whether you're building internal tools, public APIs, or microservices, Scalar-Go makes it incredibly easy to generate stunning, interactive API documentation that your developers will actually want to use.

✨ Why Choose Scalar-Go?

  • 🎨 Beautiful by Default: Professional-looking docs with multiple themes and layouts
  • ⚡ Lightning Fast: Generate documentation in milliseconds, not minutes
  • 🔧 Incredibly Flexible: Support for files, URLs, embedded specs, and runtime modifications
  • 🌍 Universal: Works with any OpenAPI 3.x specification
  • 📱 Mobile-First: Responsive design that looks great on all devices
  • 🎭 Highly Customizable: Custom CSS, themes, and UI options
  • 📊 Production Ready: Used by teams worldwide for mission-critical documentation

🛠️ Installation

go get github.com/bdpiprava/scalar-go

🎯 Quick Start

Get your API documentation up and running in under 30 seconds:

package main

import (
	"fmt"
	"net/http"
	scalargo "github.com/bdpiprava/scalar-go"
)

func main() {
	http.HandleFunc("/docs", func(w http.ResponseWriter, r *http.Request) {
		// Generate beautiful docs from your OpenAPI spec
		html, err := scalargo.NewV2(
			scalargo.WithSpecDir("./api"), // or WithSpecURL, WithSpecBytes
		)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		fmt.Fprint(w, html)
	})

	fmt.Println("📚 API Docs available at: http://localhost:8080/docs")
	http.ListenAndServe(":8080", nil)
}

📚 Interactive Demo: Visit https://bdpiprava.github.io/scalar-go to see all examples in action!

🔥 Core Features

📁 Multiple Spec Sources (Priority Order)

Load your OpenAPI specifications from anywhere:

  1. 🌐 Remote URLs (highest priority) - Perfect for CI/CD and external specs
  2. 📂 Local Directories - Great for development and file-based workflows
  3. 💾 Embedded Bytes (lowest priority) - Ideal for self-contained deployments

💡 Pro Tip: Mix and match sources! Scalar-Go automatically picks the best available source.

🌐 Remote URL Loading

Perfect for loading specs from GitHub, CDNs, or your API servers:

// Load from GitHub, CDN, or any public URL
html, err := scalargo.NewV2(
    scalargo.WithSpecURL("https://petstore3.swagger.io/api/v3/openapi.json"),
    scalargo.WithMetaDataOpts(
       scalargo.WithTitle("🐾 Pet Store API"),
        scalargo.WithKeyValue("description", "The most comprehensive pet store API"),
    ),
)
	

// Load your company's API spec from private repos
html, err := scalargo.NewV2(
    scalargo.WithSpecURL("https://api.yourcompany.com/openapi.yaml"),
    scalargo.WithTheme(scalargo.ThemeMoon), // Dark theme
)
📂 Directory-Based Loading

Great for local development and organized spec files:

// Load from directory with default filename (api.yaml)
html, err := scalargo.NewV2(
    scalargo.WithSpecDir("./docs/api"),
)

// Specify custom filename
html, err := scalargo.NewV2(
    scalargo.WithSpecDir("./specs"),
    scalargo.WithBaseFileName("petstore.yaml"), // or .json
)

// Legacy support (still works, but use NewV2 for new projects)
html, err := scalargo.New("/path/to/specs/") // ⚠️ Consider migrating to NewV2
🗂️ Multi-File Specifications

Perfect for large APIs with organized file structures. Scalar-Go automatically combines segmented files:

📁 /api-specs/
├── 📄 api.yaml           # Main specification file
├── 📁 schemas/           # Data models and schemas
│   ├── 📄 User.yaml
│   ├── 📄 Pet.yaml
│   └── 📄 Order.yaml
├── 📁 paths/             # API endpoints
│   ├── 📄 users.yaml
│   ├── 📄 pets.yaml
│   └── 📄 orders.yaml
└── 📁 responses/         # Reusable responses
    └── 📄 Error.yaml
// Scalar-Go intelligently combines all files
html, err := scalargo.NewV2(
    scalargo.WithSpecDir("./api-specs"),
    scalargo.WithTheme(scalargo.ThemeDefault),
)
// ✨ Automatically merges schemas/, paths/, and responses/ into main spec
💾 Embedded Specifications

Build self-contained applications with embedded specs - perfect for containers and serverless:

package main

import (
	_ "embed" // Enable embed functionality
	scalargo "github.com/bdpiprava/scalar-go"
)

//go:embed openapi.yaml
var apiSpec []byte

//go:embed company-logo.css
var customCSS string

func generateDocs() (string, error) {
	return scalargo.NewV2(
		// 🚀 Zero external dependencies!
		scalargo.WithSpecBytes(apiSpec),
		scalargo.WithOverrideCSS(customCSS),
		scalargo.WithTheme(scalargo.ThemePurple),
	)
}

// Or create specs programmatically
func dynamicSpec() (string, error) {
	spec := []byte(`
openapi: 3.0.0
info:
  title: "🚀 Dynamic API"
  version: "1.0.0"
  description: "Generated at runtime!"
paths:
  /health:
    get:
      summary: Health Check
      responses:
        '200':
          description: OK
`)

	return scalargo.NewV2(
		scalargo.WithSpecBytes(spec),
		scalargo.WithDarkMode(), // 🌙 Dark mode by default
	)
}

🎯 Use Cases: Docker containers, AWS Lambda, single-binary deployments, offline documentation

🎨 Customization Showcase

Make your documentation uniquely yours with extensive customization options:

🌈 Stunning Themes

Choose from professionally designed themes:

// 🌟 Available Themes
scalargo.ThemeDefault // Clean, professional
scalargo.ThemeMoon    // Dark with blue accents  
scalargo.ThemePurple     // Vibrant purple vibes
scalargo.ThemeSolarized  // Easy on the eyes
scalargo.ThemeBluePlanet // Space-age blue
scalargo.ThemeDeepSpace // Deep cosmic theme
scalargo.ThemeSaturn    // Ringed planet aesthetics
scalargo.ThemeKepler     // Exoplanet explorer
scalargo.ThemeMars       // Red planet inspired

// Apply any theme
html, err := scalargo.NewV2(
    scalargo.WithSpecURL("https://api.example.com/openapi.json"),
    scalargo.WithTheme(scalargo.ThemeMoon), // 🌙
)
📐 Layout Options
// Modern (default) - Contemporary, spacious design
scalargo.WithLayout(scalargo.LayoutModern)

// Classic - Traditional documentation feel
scalargo.WithLayout(scalargo.LayoutClassic)
🎛️ UI Controls
html, err := scalargo.NewV2(
scalargo.WithSpecDir("./api"),

// Visibility Controls
scalargo.WithSidebarVisibility(false), // Hide sidebar for focus
scalargo.WithHideModels(),             // Hide schema models
scalargo.WithHideDownloadButton(), // Remove download option

// Dark Mode Options
scalargo.WithDarkMode(), // Default to dark mode
scalargo.WithForceDarkMode(), // Lock to dark mode
scalargo.WithHideDarkModeToggle(), // Remove theme switcher

// Advanced Options
scalargo.WithSearchHotKey("ctrl+k"), // Custom search shortcut
scalargo.WithHiddenClients("curl", "php"), // Hide specific code examples
scalargo.WithHideAllClients(), // Hide all code examples
)
🎨 Custom Styling
customCSS := `
/* Your brand colors and fonts */
:root {
  --scalar-color-1: #ff6b6b;
  --scalar-color-2: #4ecdc4;
  --scalar-font: 'Inter', sans-serif;
}

/* Custom component styling */
.section-header {
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
`

html, err := scalargo.NewV2(
    scalargo.WithSpecDir("./api"),
    scalargo.WithOverrideCSS(customCSS),
    scalargo.WithTheme(scalargo.ThemeDefault),
)
📊 Metadata & Branding
html, err := scalargo.NewV2(
    scalargo.WithSpecURL("https://api.company.com/openapi.yaml"),
    scalargo.WithMetaDataOpts(
        scalargo.WithTitle("🚀 CompanyName API Hub"),
        scalargo.WithKeyValue("description", "The definitive API reference"),
        scalargo.WithKeyValue("logo", "https://company.com/logo.png"),
    ),
)
🔐 Authentication Configuration

Scalar-Go provides comprehensive authentication support for modern APIs, including API Keys, HTTP Basic/Bearer, and OAuth2 flows.

Enhanced API Key Authentication
// Simple API Key (header-based, backward compatible)
scalargo.WithAuthenticationOpts(
    scalargo.WithAPIKey("your-api-key"),
)

// Custom header name
scalargo.WithAuthenticationOpts(
    scalargo.WithAPIKey("your-api-key", scalargo.WithAPIKeyName("X-API-Key")),
)

// Query parameter-based API Key
scalargo.WithAuthenticationOpts(
    scalargo.WithAPIKeyQuery("api_key", "your-api-key"),
)

// Cookie-based API Key
scalargo.WithAuthenticationOpts(
    scalargo.WithAPIKeyCookie("session_token", "your-token"),
)
HTTP Basic & Bearer Authentication
// HTTP Basic Auth
scalargo.WithAuthenticationOpts(
    scalargo.WithHTTPBasicAuth("username", "password"),
)

// HTTP Bearer Token
scalargo.WithAuthenticationOpts(
    scalargo.WithHTTPBearerToken("your-bearer-token"),
)
OAuth2 Authentication

Full OAuth2 support with all standard flows and PKCE.

Authorization Code Flow (Recommended)

scalargo.WithAuthenticationOpts(
    scalargo.WithOAuth2AuthorizationCode(
        "https://auth.example.com/oauth/authorize",
        "https://auth.example.com/oauth/token",
        scalargo.WithOAuth2ClientID("my-client-id"),
        scalargo.WithOAuth2RedirectURI("https://myapp.com/callback"),
        scalargo.WithOAuth2PKCE(scalargo.PKCES256), // SHA-256 PKCE (recommended)
        scalargo.WithOAuth2Scopes("read:api", "write:api"),
    ),
)

Client Credentials Flow

scalargo.WithAuthenticationOpts(
    scalargo.WithOAuth2ClientCredentials(
        "https://auth.example.com/oauth/token",
        scalargo.WithOAuth2ClientID("service-account"),
        scalargo.WithOAuth2ClientSecret("super-secret"),
    ),
)

Advanced OAuth2 Customization

scalargo.WithAuthenticationOpts(
    scalargo.WithOAuth2AuthorizationCode(
        "https://auth.example.com/oauth/authorize",
        "https://auth.example.com/oauth/token",
        scalargo.WithOAuth2ClientID("my-client"),
        scalargo.WithOAuth2CustomToken("custom_access_token"), // Custom token field name
        scalargo.WithOAuth2AdditionalAuthParams(map[string]string{
            "audience": "https://api.example.com",
        }),
        scalargo.WithOAuth2AdditionalTokenParams(map[string]string{
            "resource": "https://resource.example.com",
        }),
        scalargo.WithOAuth2CredentialsLocation(scalargo.OAuth2CredentialsHeader),
    ),
)
Multiple Security Schemes

Configure multiple authentication methods for your API:

scalargo.WithAuthenticationOpts(
    // Define multiple security schemes
    scalargo.WithSecurityScheme("api_key",
        scalargo.APIKeyScheme("X-API-Key", scalargo.APIKeyLocationHeader, "default-key"),
    ),
    scalargo.WithSecurityScheme("bearer_auth",
        scalargo.BearerScheme("default-token"),
    ),
    scalargo.WithSecurityScheme("oauth2",
        scalargo.OAuth2Scheme(
            scalargo.OAuth2FlowAuthorizationCode,
            scalargo.OAuth2Config{
                AuthorizationURL: "https://auth.example.com/authorize",
                TokenURL:         "https://auth.example.com/token",
                ClientID:         "my-client",
                UsePKCE:          scalargo.PKCES256,
                SelectedScopes:   []string{"read:api", "write:api"},
            },
        ),
    ),
    // Set preferred security scheme
    scalargo.WithPreferredSecurityScheme("bearer_auth"),
)

PKCE Modes:

  • scalargo.PKCES256 - SHA-256 PKCE (recommended for production)
  • scalargo.PKCEPlain - Plain PKCE
  • scalargo.PKCEDisabled - Disable PKCE

OAuth2 Credentials Location:

  • scalargo.OAuth2CredentialsHeader - Send credentials in Authorization header (default)
  • scalargo.OAuth2CredentialsBody - Send credentials in request body

🚀 Real-World Examples

🏢 Enterprise API Documentation
package main

import (
	"fmt"
	"net/http"
	scalargo "github.com/bdpiprava/scalar-go"
	"github.com/bdpiprava/scalar-go/model"
)

func main() {
	// Multiple API versions with custom branding
	http.HandleFunc("/docs/v1", generateV1Docs)
	http.HandleFunc("/docs/v2", generateV2Docs)
	http.HandleFunc("/docs/internal", generateInternalDocs)

	fmt.Println("🏢 Enterprise API Hub:")
	fmt.Println("   📚 Public API v1:  http://localhost:8080/docs/v1")
	fmt.Println("   🚀 Public API v2:  http://localhost:8080/docs/v2")
	fmt.Println("   🔒 Internal APIs:  http://localhost:8080/docs/internal")

	http.ListenAndServe(":8080", nil)
}

func generateV1Docs(w http.ResponseWriter, r *http.Request) {
	html, err := scalargo.NewV2(
		scalargo.WithSpecDir("./specs/v1"),
		scalargo.WithTheme(scalargo.ThemeDefault),
		scalargo.WithMetaDataOpts(
			scalargo.WithTitle("🏢 Company API v1.0"),
			scalargo.WithKeyValue("description", "Stable production API"),
		),
		// Add environment-specific server URLs
		scalargo.WithSpecModifier(func(spec *model.Spec) *model.Spec {
			spec.Servers = []model.Server{
				{URL: "https://api.company.com/v1", Description: "Production"},
				{URL: "https://staging-api.company.com/v1", Description: "Staging"},
			}
			return spec
		}),
	)

	if err != nil {
		http.Error(w, fmt.Sprintf("Documentation error: %v", err), 500)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprint(w, html)
}

func generateV2Docs(w http.ResponseWriter, r *http.Request) {
	html, err := scalargo.NewV2(
		scalargo.WithSpecURL("https://github.com/company/api-specs/raw/main/v2.yaml"),
		scalargo.WithTheme(scalargo.ThemeMoon), // Modern dark theme
		scalargo.WithDarkMode(),
		scalargo.WithMetaDataOpts(
			scalargo.WithTitle("🚀 Company API v2.0 (Beta)"),
			scalargo.WithKeyValue("description", "Next-generation API with GraphQL support"),
		),
	)

	if err != nil {
		http.Error(w, fmt.Sprintf("Documentation error: %v", err), 500)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprint(w, html)
}

func generateInternalDocs(w http.ResponseWriter, r *http.Request) {
	// Internal documentation with restricted styling
	html, err := scalargo.NewV2(
		scalargo.WithSpecDir("./internal-specs"),
		scalargo.WithTheme(scalargo.ThemeSolarized),
		scalargo.WithHideDownloadButton(),                // Prevent spec downloads
		scalargo.WithHiddenClients("curl", "javascript"), // Hide external clients
		scalargo.WithOverrideCSS(`
            .section-header::before {
                content: "🔒 INTERNAL ";
                color: #ff6b6b;
                font-weight: bold;
            }
        `),
	)

	if err != nil {
		http.Error(w, fmt.Sprintf("Documentation error: %v", err), 500)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprint(w, html)
}
🐳 Containerized Microservice Documentation
package main

import (
	_ "embed"
	"fmt"
	"net/http"
	"os"
	scalargo "github.com/bdpiprava/scalar-go"
	"github.com/bdpiprava/scalar-go/model"
)

//go:embed openapi.yaml
var apiSpec []byte

//go:embed assets/custom.css
var brandingCSS string

func main() {
	// Health check endpoint
	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, `{"status": "healthy", "service": "api-docs"}`)
	})

	// Self-contained documentation
	http.HandleFunc("/docs", func(w http.ResponseWriter, r *http.Request) {
		html, err := scalargo.NewV2(
			scalargo.WithSpecBytes(apiSpec), // 🚀 No external files needed!
			scalargo.WithTheme(scalargo.ThemeBluePlanet),
			scalargo.WithOverrideCSS(brandingCSS),

			// Dynamic environment-based configuration
			scalargo.WithSpecModifier(func(spec *model.Spec) *model.Spec {
				env := os.Getenv("ENVIRONMENT")
				if env == "" {
					env = "development"
				}

				// Dynamic title with environment
				spec.Info.Title = fmt.Sprintf("%s (%s)", spec.Info.Title, env)

				// Environment-specific servers
				switch env {
				case "production":
					spec.Servers = []model.Server{
						{URL: "https://api.company.com", Description: "Production API"},
					}
				case "staging":
					spec.Servers = []model.Server{
						{URL: "https://staging.company.com", Description: "Staging API"},
					}
				default:
					spec.Servers = []model.Server{
						{URL: "http://localhost:8080", Description: "Development API"},
					}
				}

				return spec
			}),
		)

		if err != nil {
			http.Error(w, fmt.Sprintf("Documentation generation failed: %v", err), 500)
			return
		}

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.Header().Set("Cache-Control", "public, max-age=3600") // Cache for 1 hour
		fmt.Fprint(w, html)
	})

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	fmt.Printf("🐳 Containerized API Documentation\n")
	fmt.Printf("   📚 Documentation: http://localhost:%s/docs\n", port)
	fmt.Printf("   💚 Health Check:  http://localhost:%s/health\n", port)

	http.ListenAndServe(":"+port, nil)
}
🔄 Dynamic Runtime Modification
func advancedSpecModification() (string, error) {
    return scalargo.NewV2(
        scalargo.WithSpecDir("./api"),
        scalargo.WithSpecModifier(func (spec *model.Spec) *model.Spec {
            // Add build information
            buildTime := time.Now().Format("2006-01-02 15:04:05")
            spec.Info.Description = fmt.Sprintf("%s\n\n**Last Updated:** %s", *spec.Info.Description, buildTime)
            
            // Add API statistics
            paths := spec.DocumentedPaths()
            spec.Info.Description = fmt.Sprintf("%s\n**Total Endpoints:** %d", *spec.Info.Description, len(paths))
            
            // Add custom tags
            spec.Tags = append(spec.Tags, model.Tag{
                Name:        "build-info",
                Description: "Automatically generated build information",
            })
            
            return spec
        }),
        scalargo.WithTheme(scalargo.ThemePurple),
    )
}

🎯 Specification Source Priority

Scalar-Go intelligently handles multiple spec sources with a clear priority system:

// 🎯 Priority Demonstration
html, err := scalargo.NewV2(
    // 🥇 1st Priority: Remote URL (if provided)
    scalargo.WithSpecURL("https://api.example.com/openapi.yaml"),
    
    // 🥈 2nd Priority: Local Directory (fallback if URL fails)
    scalargo.WithSpecDir("./backup-specs"),
    
    // 🥉 3rd Priority: Embedded Bytes (ultimate fallback)
    scalargo.WithSpecBytes(embeddedSpec),
    
    // ✨ These always apply regardless of source
    scalargo.WithTheme(scalargo.ThemeMoon),
    scalargo.WithDarkMode(),
)

🧠 Smart Behavior:

  • URL Available? → Load from URL, ignore directory and bytes
  • URL Failed? → Try directory, ignore bytes
  • Directory Failed? → Use embedded bytes
  • All Failed? → Return helpful error message

💡 Pro Tip: Use this for robust deployments! URL for latest specs, directory for local dev, bytes for offline fallback.

📖 Comprehensive Examples

Explore real-world implementations in our examples directory:

📚 Interactive Demo: Visit https://bdpiprava.github.io/scalar-go to see all examples in action!

🚀 Advanced Use Cases

📊 Multi-Tenant API Documentation
func tenantSpecificDocs(tenantID string) (string, error) {
    return scalargo.NewV2(
        scalargo.WithSpecURL(fmt.Sprintf("https://specs.company.com/%s/api.yaml", tenantID)),
        scalargo.WithSpecModifier(func (spec *model.Spec) *model.Spec {
            spec.Info.Title = fmt.Sprintf("%s - %s API", strings.Title(tenantID), spec.Info.Title)
            spec.Servers = []model.Server{
                {
                    URL: fmt.Sprintf("https://%s.api.company.com", tenantID)
                },
            }
            return spec
        }),
        scalargo.WithTheme(getThemeForTenant(tenantID)),
    )
}
🔄 CI/CD Integration
// Perfect for automated documentation updates
func generateDocsForBranch(branch string) {
    html, _ := scalargo.NewV2(
        scalargo.WithSpecURL(fmt.Sprintf("https://raw.githubusercontent.com/company/api-specs/%s/openapi.yaml", branch)),
        scalargo.WithMetaDataOpts(
            scalargo.WithTitle(fmt.Sprintf("API Docs - %s branch", branch)),
            scalargo.WithKeyValue("build", os.Getenv("BUILD_NUMBER")),
        ),
    )
// Deploy to branch-specific documentation site
}
🎨 White-Label Documentation
func whitelabelDocs(customerConfig CustomerConfig) (string, error) {
    customCSS := fmt.Sprintf(`
        :root {
            --primary-color: %s;
            --logo-url: url('%s');
        }
        .navbar-brand::before {
            content: '';
            background-image: var(--logo-url);
        }
    `, customerConfig.PrimaryColor, customerConfig.LogoURL)

    return scalargo.NewV2(
        scalargo.WithSpecBytes(customerConfig.APISpec),
        scalargo.WithOverrideCSS(customCSS),
        scalargo.WithMetaDataOpts(
            scalargo.WithTitle(customerConfig.CompanyName + " API"),
        ),
    )
}

🤝 Contributing

We ❤️ contributions! Here's how you can help:

  1. 🐛 Found a Bug? Open an issue
  2. 💡 Have an Idea? Start a discussion
  3. 🔧 Want to Contribute? Fork, code, and submit a PR!
Development Setup
git clone https://github.com/bdpiprava/scalar-go.git
cd scalar-go
go mod tidy
go test ./...

📄 License

MIT License - see LICENSE file for details.

🙏 Credits & Acknowledgments

  • Scalar Team - For creating the amazing Scalar documentation platform that powers this library
  • MarceloPetrucio - For the original Go integration that inspired this project
  • OpenAPI Initiative - For the OpenAPI specification standard
  • Go Community - For the fantastic ecosystem and tooling

Made with ❤️ for the Go community

⭐ Star this repo📖 Documentation🐛 Report Issues💬 Discussions

Documentation

Index

Constants

View Source
const (
	ClientAsyncHTTP    = "asynchttp"
	ClientAxios        = "axios"
	ClientCljHTTP      = "clj_http"
	ClientCoHTTP       = "cohttp"
	ClientCurl         = "curl"
	ClientFetch        = "fetch"
	ClientGuzzle       = "guzzle"
	ClientHTTP1        = "http1.1"
	ClientHTTPClient   = "httpclient"
	ClientHTTP2        = "http2"
	ClientHttpie       = "httpie"
	ClientHttr         = "httr"
	ClientJquery       = "jquery"
	ClientLibCurl      = "libcurl"
	ClientNative       = "native"
	ClientNetHTTP      = "nethttp"
	ClientNsurlSession = "nsurlsession"
	ClientOkHTTP       = "okhttp"
	ClientOkhttp       = "okhttp"
	ClientPython3      = "python3"
	ClientRequest      = "request"
	ClientRequests     = "requests"
	ClientRestMethod   = "restmethod"
	ClientRestSharp    = "restsharp"
	ClientUndici       = "undici"
	ClientUnirest      = "unirest"
	ClientWebRequest   = "webrequest"
	ClientWget         = "wget"
	ClientXhr          = "xhr"
	ClientHTTP         = "http"
	ClientOfetch       = "ofetch"
	ClientHTTPXSync    = "httpxsync"
	ClientHTTPXAsync   = "httpxasync"
	ClientReqWest      = "reqwest"
)

List of known clients

View Source
const DefaultCDN = "https://cdn.jsdelivr.net/npm/@scalar/api-reference"

DefaultCDN default CDN for api-reference

Variables

This section is empty.

Functions

func New

func New(apiFilesDir string, opts ...Option) (string, error)

New generates the HTML for the Scalar UI

func NewV2 added in v0.6.0

func NewV2(opts ...Option) (string, error)

NewV2 generate the HTML for the Scalar UI

func WithAuthentication

func WithAuthentication(authentication string) func(*Options)

WithAuthentication sets the authentication method for the Scalar UI

func WithAuthenticationOpts added in v0.12.0

func WithAuthenticationOpts(opts ...AuthOption) func(*Options)

WithAuthenticationOpts sets the authentication method for the Scalar UI

func WithBaseFileName

func WithBaseFileName(baseFileName string) func(*Options)

WithBaseFileName sets the base file name for the Scalar UI

func WithBaseServerURL

func WithBaseServerURL(baseServerURL string) func(*Options)

WithBaseServerURL sets the base server URL for the Scalar UI

func WithCDN

func WithCDN(cdn string) func(*Options)

WithCDN sets the CDN for the Scalar UI

func WithCustomBodyJS added in v0.13.0

func WithCustomBodyJS(js string) func(*Options)

WithCustomBodyJS injects custom JavaScript in the <body> after Scalar initialization Note: User is responsible for XSS prevention in custom JS

func WithCustomCSS added in v0.13.0

func WithCustomCSS(css string) func(*Options)

WithCustomCSS sets custom CSS in the configuration object (different from WithOverrideCSS which injects CSS in <style> tag)

func WithCustomHeadJS added in v0.13.0

func WithCustomHeadJS(js string) func(*Options)

WithCustomHeadJS injects custom JavaScript in the <head> before the Scalar CDN script Note: User is responsible for XSS prevention in custom JS

func WithDarkMode

func WithDarkMode() func(*Options)

WithDarkMode set the dark mode as default

func WithDefaultFonts

func WithDefaultFonts() func(*Options)

WithDefaultFonts sets the default fonts usage for the Scalar UI

func WithDefaultHTTPClient added in v0.13.0

func WithDefaultHTTPClient(target, client string) func(*Options)

WithDefaultHTTPClient sets the default HTTP client for code examples

func WithEditable

func WithEditable() func(*Options)

WithEditable sets the editable state for the Scalar UI

func WithForceDarkMode added in v0.5.0

func WithForceDarkMode() func(*Options)

WithForceDarkMode makes it always this state no matter what

func WithHiddenClients

func WithHiddenClients(hiddenClients ...string) func(*Options)

WithHiddenClients hide the set clients

func WithHideAllClients added in v0.6.0

func WithHideAllClients() func(*Options)

WithHideAllClients sets the hidden clients for the Scalar UI

func WithHideDarkModeToggle added in v0.5.0

func WithHideDarkModeToggle() func(*Options)

WithHideDarkModeToggle hides the dark mode toggle button

func WithHideDownloadButton

func WithHideDownloadButton() func(*Options)

WithHideDownloadButton hide to download OpenAPI spec button

func WithHideModels

func WithHideModels() func(*Options)

WithHideModels sets the models visibility for the Scalar UI

func WithHideSearch added in v0.13.0

func WithHideSearch(hide bool) func(*Options)

WithHideSearch hides or shows the search functionality in the Scalar UI

func WithKeyValue added in v0.5.0

func WithKeyValue(key string, value any) func(MetaData)

WithKeyValue add metadata with key and value

func WithLayout

func WithLayout(layout Layout) func(*Options)

WithLayout sets the layout for the Scalar UI

func WithMetaDataOpts added in v0.5.0

func WithMetaDataOpts(metadataOpts ...MetaOption) func(*Options)

WithMetaDataOpts add metadata

func WithMultipleSources added in v0.13.0

func WithMultipleSources(sources ...DocumentSource) func(*Options)

WithMultipleSources configures multiple OpenAPI document sources for multi-version API documentation

func WithOperationTitleSource added in v0.13.0

func WithOperationTitleSource(source OperationTitleSource) func(*Options)

WithOperationTitleSource sets where to get operation titles from (summary or path)

func WithOperationsSorter added in v0.13.0

func WithOperationsSorter(sorter SorterOption) func(*Options)

WithOperationsSorter sets how operations are sorted within tags

func WithOrderSchemaPropertiesBy added in v0.13.0

func WithOrderSchemaPropertiesBy(order SchemaPropertiesOrder) func(*Options)

WithOrderSchemaPropertiesBy sets how schema properties are ordered

func WithOverrideCSS

func WithOverrideCSS(overrideCSS string) func(*Options)

WithOverrideCSS sets the override CSS for the Scalar UI

func WithPathRouting

func WithPathRouting(pathRouting string) func(*Options)

WithPathRouting sets the path routing for the Scalar UI

func WithPersistAuth added in v0.13.0

func WithPersistAuth(persist bool) func(*Options)

WithPersistAuth enables or disables persisting authentication credentials in localStorage

func WithProxy

func WithProxy(proxy string) func(*Options)

WithProxy sets the proxy for the Scalar UI

func WithRenderMode added in v0.13.0

func WithRenderMode(mode RenderMode) func(*Options)

WithRenderMode sets the rendering mode for the Scalar UI

func WithSearchHotKey

func WithSearchHotKey(searchHotKey string) func(*Options)

WithSearchHotKey sets the search hot key for the Scalar UI

func WithServers added in v0.5.0

func WithServers(servers ...ServerOverride) func(*Options)

WithServers servers to override the openapi spec servers

func WithShowOperationID added in v0.13.0

func WithShowOperationID(show bool) func(*Options)

WithShowOperationID shows or hides operation IDs in the Scalar UI

func WithShowToolbar added in v0.13.0

func WithShowToolbar(visibility ShowToolbarOption) func(*Options)

WithShowToolbar controls the visibility of the developer tools toolbar Accepts: ShowToolbarAlways, ShowToolbarLocalhost, or ShowToolbarNever Default in this library: ShowToolbarNever (differs from Scalar's default of localhost)

func WithSidebarVisibility

func WithSidebarVisibility(visible bool) func(*Options)

WithSidebarVisibility sets the sidebar visibility for the Scalar UI

func WithSpecBytes added in v0.12.1

func WithSpecBytes(specBytes []byte) func(*Options)

WithSpecBytes loads the spec from the provided bytes in either YAML or JSON format

func WithSpecDir added in v0.6.0

func WithSpecDir(specDir string) func(*Options)

WithSpecDir read spec from directory

func WithSpecModifier added in v0.0.6

func WithSpecModifier(handler SpecModifier) func(*Options)

WithSpecModifier allows to modify the spec before rendering

func WithSpecURL added in v0.6.0

func WithSpecURL(specURL string) func(*Options)

WithSpecURL set the spec URL in the doc

func WithTagsSorter added in v0.13.0

func WithTagsSorter(sorter SorterOption) func(*Options)

WithTagsSorter sets how tags are sorted in the sidebar

func WithTheme

func WithTheme(theme Theme) func(*Options)

WithTheme sets the theme for the Scalar UI

func WithTitle added in v0.5.0

func WithTitle(title string) func(MetaData)

WithTitle add title with value in metadata

Types

type APIKeyConfig added in v0.13.0

type APIKeyConfig struct {
	Token string         `json:"token"`
	Name  string         `json:"name,omitempty"`
	In    APIKeyLocation `json:"in,omitempty"`
}

APIKeyConfig holds API key configuration

type APIKeyLocation added in v0.13.0

type APIKeyLocation string

APIKeyLocation specifies where the API key is transmitted

const (
	APIKeyLocationHeader APIKeyLocation = "header"
	APIKeyLocationQuery  APIKeyLocation = "query"
	APIKeyLocationCookie APIKeyLocation = "cookie"
)

type APIKeyOption added in v0.13.0

type APIKeyOption func(*APIKeyConfig)

APIKeyOption configures API key authentication

func WithAPIKeyLocation added in v0.13.0

func WithAPIKeyLocation(location APIKeyLocation) APIKeyOption

WithAPIKeyLocation sets where the API key is sent

func WithAPIKeyName added in v0.13.0

func WithAPIKeyName(name string) APIKeyOption

WithAPIKeyName sets the parameter name for the API key

type AuthOption added in v0.12.0

type AuthOption func(AuthenticationOption)

func WithAPIKey added in v0.12.0

func WithAPIKey(token string, opts ...APIKeyOption) AuthOption

WithAPIKey configures API key authentication with optional configuration

func WithAPIKeyCookie added in v0.13.0

func WithAPIKeyCookie(name, token string) AuthOption

WithAPIKeyCookie is a shorthand for cookie-based API keys

func WithAPIKeyHeader added in v0.13.0

func WithAPIKeyHeader(name, token string) AuthOption

WithAPIKeyHeader is a shorthand for header-based API keys

func WithAPIKeyQuery added in v0.13.0

func WithAPIKeyQuery(name, token string) AuthOption

WithAPIKeyQuery is a shorthand for query parameter-based API keys

func WithCustomSecurity added in v0.12.0

func WithCustomSecurity() AuthOption

WithCustomSecurity sets the custom security toggle to true

func WithHTTPBasicAuth added in v0.12.0

func WithHTTPBasicAuth(username, password string) AuthOption

WithHTTPBasicAuth sets the HTTP Basic Auth options

func WithHTTPBearerToken added in v0.12.0

func WithHTTPBearerToken(token string) AuthOption

WithHTTPBearerToken sets the HTTP Bearer Token options

func WithOAuth2AuthorizationCode added in v0.13.0

func WithOAuth2AuthorizationCode(authorizationURL, tokenURL string, opts ...OAuth2Option) AuthOption

WithOAuth2AuthorizationCode configures OAuth2 Authorization Code flow

func WithOAuth2ClientCredentials added in v0.13.0

func WithOAuth2ClientCredentials(tokenURL string, opts ...OAuth2Option) AuthOption

WithOAuth2ClientCredentials configures OAuth2 Client Credentials flow

func WithOAuth2Implicit added in v0.13.0

func WithOAuth2Implicit(authorizationURL string, opts ...OAuth2Option) AuthOption

WithOAuth2Implicit configures OAuth2 Implicit flow (deprecated but supported for compatibility)

func WithOAuth2Password added in v0.13.0

func WithOAuth2Password(tokenURL string, opts ...OAuth2Option) AuthOption

WithOAuth2Password configures OAuth2 Password flow (deprecated but supported for compatibility)

func WithPreferredSecurityScheme added in v0.12.0

func WithPreferredSecurityScheme(schemes ...any) AuthOption

WithPreferredSecurityScheme sets the preferred security scheme Acceptable values: 1. Single security scheme: "my_custom_security_scheme" 2. Multiple security schemes: "my_custom_security_scheme", "another_security_scheme" 3. Complex security schemes: ["my_custom_security_scheme", "another_security_scheme"], "yet-another_security_scheme"

func WithSecurityScheme added in v0.13.0

func WithSecurityScheme(name string, config SecuritySchemeConfig) AuthOption

WithSecurityScheme adds a named security scheme configuration

type AuthenticationOption added in v0.12.0

type AuthenticationOption map[string]any

type DocumentSource added in v0.13.0

type DocumentSource struct {
	Title   string `json:"title,omitempty"`   // Display title for this document
	Slug    string `json:"slug,omitempty"`    // URL slug for routing
	URL     string `json:"url,omitempty"`     // URL to fetch the OpenAPI document
	Content string `json:"content,omitempty"` // Inline OpenAPI document content (mutually exclusive with URL)
	Default bool   `json:"default,omitempty"` // Whether this is the default document to display
}

DocumentSource represents a single OpenAPI document source for multi-document configurations

type HTTPClientConfig added in v0.13.0

type HTTPClientConfig struct {
	TargetKey string `json:"targetKey"` // Target language/platform (e.g., "node", "php", "python")
	ClientKey string `json:"clientKey"` // Specific client library (e.g., "undici", "guzzle", "requests")
}

HTTPClientConfig configures the default HTTP client to use in the Scalar UI

type Layout

type Layout string

Layout represents different layout options

const (
	LayoutModern  Layout = "modern"
	LayoutClassic Layout = "classic"
)

type MetaData added in v0.5.0

type MetaData map[string]any

MetaData metadata information for Scalar UI

type MetaOption added in v0.5.0

type MetaOption func(MetaData)

type OAuth2Config added in v0.13.0

type OAuth2Config struct {
	AuthorizationURL    string                    `json:"authorizationUrl,omitempty"`
	TokenURL            string                    `json:"tokenUrl,omitempty"`
	ClientID            string                    `json:"x-scalar-client-id,omitempty"`
	ClientSecret        string                    `json:"clientSecret,omitempty"`
	RedirectURI         string                    `json:"x-scalar-redirect-uri,omitempty"`
	UsePKCE             OAuth2PKCEMode            `json:"x-usePkce,omitempty"`
	SelectedScopes      []string                  `json:"selectedScopes,omitempty"`
	SecurityQuery       map[string]string         `json:"x-scalar-security-query,omitempty"`
	SecurityBody        map[string]string         `json:"x-scalar-security-body,omitempty"`
	TokenName           string                    `json:"x-tokenName,omitempty"`
	CredentialsLocation OAuth2CredentialsLocation `json:"x-scalar-credentials-location,omitempty"`
}

OAuth2Config holds OAuth2 flow configuration

type OAuth2CredentialsLocation added in v0.13.0

type OAuth2CredentialsLocation string

OAuth2CredentialsLocation specifies where credentials are sent

const (
	OAuth2CredentialsHeader OAuth2CredentialsLocation = "header"
	OAuth2CredentialsBody   OAuth2CredentialsLocation = "body"
)

type OAuth2FlowType added in v0.13.0

type OAuth2FlowType string

OAuth2FlowType represents different OAuth2 flow types

const (
	OAuth2FlowAuthorizationCode OAuth2FlowType = "authorizationCode"
	OAuth2FlowClientCredentials OAuth2FlowType = "clientCredentials"
	OAuth2FlowImplicit          OAuth2FlowType = "implicit"
	OAuth2FlowPassword          OAuth2FlowType = "password"
)

type OAuth2Option added in v0.13.0

type OAuth2Option func(*OAuth2Config)

OAuth2Option configures OAuth2 authentication

func WithOAuth2AdditionalAuthParams added in v0.13.0

func WithOAuth2AdditionalAuthParams(params map[string]string) OAuth2Option

WithOAuth2AdditionalAuthParams adds additional query parameters to the authorization endpoint

func WithOAuth2AdditionalTokenParams added in v0.13.0

func WithOAuth2AdditionalTokenParams(params map[string]string) OAuth2Option

WithOAuth2AdditionalTokenParams adds additional body parameters to the token endpoint

func WithOAuth2ClientID added in v0.13.0

func WithOAuth2ClientID(clientID string) OAuth2Option

WithOAuth2ClientID sets the OAuth2 client ID

func WithOAuth2ClientSecret added in v0.13.0

func WithOAuth2ClientSecret(clientSecret string) OAuth2Option

WithOAuth2ClientSecret sets the OAuth2 client secret

func WithOAuth2CredentialsLocation added in v0.13.0

func WithOAuth2CredentialsLocation(location OAuth2CredentialsLocation) OAuth2Option

WithOAuth2CredentialsLocation sets where client credentials are sent

func WithOAuth2CustomToken added in v0.13.0

func WithOAuth2CustomToken(tokenName string) OAuth2Option

WithOAuth2CustomToken sets a custom token field name

func WithOAuth2PKCE added in v0.13.0

func WithOAuth2PKCE(mode OAuth2PKCEMode) OAuth2Option

WithOAuth2PKCE enables PKCE with the specified mode

func WithOAuth2RedirectURI added in v0.13.0

func WithOAuth2RedirectURI(redirectURI string) OAuth2Option

WithOAuth2RedirectURI sets the OAuth2 redirect URI

func WithOAuth2Scopes added in v0.13.0

func WithOAuth2Scopes(scopes ...string) OAuth2Option

WithOAuth2Scopes sets the pre-selected OAuth2 scopes

type OAuth2PKCEMode added in v0.13.0

type OAuth2PKCEMode string

OAuth2PKCEMode represents PKCE configuration modes

const (
	PKCES256     OAuth2PKCEMode = "S256"
	PKCEPlain    OAuth2PKCEMode = "plain"
	PKCEDisabled OAuth2PKCEMode = "no"
)

type OperationTitleSource added in v0.13.0

type OperationTitleSource string

OperationTitleSource defines where to get operation titles from

const (
	// OperationTitleSourceSummary uses the summary field
	OperationTitleSourceSummary OperationTitleSource = "summary"
	// OperationTitleSourcePath uses the path
	OperationTitleSourcePath OperationTitleSource = "path"
)

type Option

type Option func(*Options)

type Options

type Options struct {
	Configurations map[string]any
	OverrideCSS    string
	BaseFileName   string
	CDN            string
	SpecModifier   SpecModifier
	SpecDirectory  string
	SpecURL        string
	SpecBytes      []byte
	RenderMode     RenderMode
	CustomHeadJS   string // Custom JavaScript to inject in <head> before Scalar CDN script
	CustomBodyJS   string // Custom JavaScript to inject in <body> after Scalar initialization
}

func (*Options) BuildInitScript added in v0.13.0

func (o *Options) BuildInitScript() (string, error)

BuildInitScript generates JavaScript initialization code for JavaScript API mode Returns: Scalar.createApiReference('#api-reference', {config});

func (*Options) GetSpecScript added in v0.6.0

func (o *Options) GetSpecScript() (string, error)

GetSpecScript prepares and returns the spec script, routing to appropriate method based on RenderMode

type RenderMode added in v0.13.0

type RenderMode string

RenderMode defines how Scalar initializes in the HTML output

const (
	// RenderModeDataAttribute uses data attributes on script tag (legacy, available for backward compatibility)
	RenderModeDataAttribute RenderMode = "data-attribute"
	// RenderModeJavaScriptAPI uses Scalar.createApiReference() JavaScript API (recommended, default)
	RenderModeJavaScriptAPI RenderMode = "javascript-api"
)

type SchemaPropertiesOrder added in v0.13.0

type SchemaPropertiesOrder string

SchemaPropertiesOrder defines how to order schema properties

const (
	// SchemaPropertiesOrderAlpha sorts properties alphabetically
	SchemaPropertiesOrderAlpha SchemaPropertiesOrder = "alpha"
	// SchemaPropertiesOrderPreserve preserves the order from the spec
	SchemaPropertiesOrderPreserve SchemaPropertiesOrder = "preserve"
)

type SecuritySchemeConfig added in v0.13.0

type SecuritySchemeConfig map[string]any

SecuritySchemeConfig represents configuration for a single security scheme

func APIKeyScheme added in v0.13.0

func APIKeyScheme(name string, location APIKeyLocation, value string) SecuritySchemeConfig

APIKeyScheme creates an API key security scheme configuration

func BasicScheme added in v0.13.0

func BasicScheme(username, password string) SecuritySchemeConfig

BasicScheme creates a basic auth security scheme configuration

func BearerScheme added in v0.13.0

func BearerScheme(token string) SecuritySchemeConfig

BearerScheme creates a bearer token security scheme configuration

func OAuth2Scheme added in v0.13.0

func OAuth2Scheme(flow OAuth2FlowType, config OAuth2Config) SecuritySchemeConfig

OAuth2Scheme creates an OAuth2 security scheme configuration

type Server deprecated added in v0.5.0

type Server = ServerOverride

Server is alias exists for backwards compatibility but will be removed in a future version. The name was changed to avoid collision with model.Server.

Deprecated: use ServerOverride instead.

type ServerOverride added in v0.13.0

type ServerOverride struct {
	URL         string `json:"url"`
	Description string `json:"description"`
}

ServerOverride represents server override configuration for UI display. This is a simplified version of model.Server, used to quickly override server URLs without needing the full OpenAPI server specification.

type ShowToolbarOption added in v0.13.0

type ShowToolbarOption string

ShowToolbarOption defines when to display the developer tools toolbar

const (
	// ShowToolbarAlways displays the toolbar in all environments
	ShowToolbarAlways ShowToolbarOption = "always"
	// ShowToolbarLocalhost displays toolbar only on localhost or similar hosts (Scalar default)
	ShowToolbarLocalhost ShowToolbarOption = "localhost"
	// ShowToolbarNever never displays the toolbar
	ShowToolbarNever ShowToolbarOption = "never"
)

type SorterOption added in v0.13.0

type SorterOption string

SorterOption defines sorting behavior for tags and operations

const (
	// SorterAlpha sorts alphabetically
	SorterAlpha SorterOption = "alpha"
	// SorterMethod sorts by HTTP method (for operations only)
	SorterMethod SorterOption = "method"
)

type SpecModifier added in v0.0.6

type SpecModifier func(spec *model.Spec) *model.Spec

SpecModifier is a function that can be used to override the spec

type Theme

type Theme string

Theme as a type based on string for theme identification

const (
	ThemeDefault    Theme = "default"
	ThemeAlternate  Theme = "alternate"
	ThemeMoon       Theme = "moon"
	ThemePurple     Theme = "purple"
	ThemeSolarized  Theme = "solarized"
	ThemeBluePlanet Theme = "bluePlanet"
	ThemeDeepSpace  Theme = "deepSpace"
	ThemeSaturn     Theme = "saturn"
	ThemeKepler     Theme = "kepler"
	ThemeMars       Theme = "mars"
	ThemeNone       Theme = "none"
	ThemeNil        Theme = ""
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL