openapi

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2026 License: MIT Imports: 16 Imported by: 0

README

OpenAPI

tag Go Reference Go Report Card CI codecov License

Automatic OpenAPI 3.0.4 and 3.1.2 specification generation for Go applications.

Features

  • Type-Driven - Define structs, get OpenAPI specs automatically
  • OpenAPI 3.0.4 and 3.1.2 - Support for both major versions
  • Rich Metadata - Six tag systems for complete control
  • Validation Integration - Transform validation rules into schema constraints
  • Security Schemes - Built-in support for all OpenAPI auth types
  • Examples - Auto-generate or provide custom examples
  • Extensible - Hooks for custom schema transformations

Installation

go get github.com/talav/openapi

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/talav/openapi"
)

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

type CreateUserRequest struct {
    Body struct {
        Name  string `json:"name" validate:"required"`
        Email string `json:"email" validate:"required,email"`
    } `body:"structured"`
}

func main() {
    api := openapi.NewAPI(
        openapi.WithInfoTitle("My API"),
        openapi.WithInfoVersion("1.0.0"),
        openapi.WithInfoDescription("API for managing users"),
        openapi.WithServer("http://localhost:8080", "Local development"),
        openapi.WithBearerAuth("bearerAuth", "JWT authentication"),
    )

    result, err := api.Generate(context.Background(),
        openapi.GET("/users/:id",
            openapi.WithSummary("Get user"),
            openapi.WithResponse(200, User{}),
            openapi.WithSecurity("bearerAuth"),
        ),
        openapi.POST("/users",
            openapi.WithSummary("Create user"),
            openapi.WithRequest(CreateUserRequest{}),
            openapi.WithResponse(201, User{}),
        ),
        openapi.DELETE("/users/:id",
            openapi.WithSummary("Delete user"),
            openapi.WithResponse(204, nil),
            openapi.WithSecurity("bearerAuth"),
        ),
    )
    if err != nil {
        log.Fatal(err)
    }

    // Check for warnings (optional)
    if len(result.Warnings) > 0 {
        fmt.Printf("Generated with %d warnings\n", len(result.Warnings))
    }

    fmt.Println(string(result.JSON))
}

Documentation

Full Documentation →

Getting Started
Guides
Advanced
API Reference

Key Concepts

Struct Tags

The library uses six struct tags:

type Request struct {
    ID      int    `schema:"id,location=path"`        // Parameter metadata
    APIKey  string `schema:"X-API-Key,location=header"` // Header parameter
    
    Body struct {
        Name  string `json:"name" validate:"required,min=3"`  // Validation
        Email string `json:"email" validate:"required,email" openapi:"description=Contact email,[email protected]"` // Metadata
        Age   int    `json:"age" default:"18"` // Default value
    } `body:"structured"` // Request body
}
  • json - Property names
  • schema - Parameter location and style
  • body - Request/response body
  • validate - Validation rules → schema constraints
  • openapi - OpenAPI metadata (descriptions, examples)
  • default - Default values
  • requires - Conditional required fields
Tag Semantics

OpenAPI consumes the same schema and body tag semantics as talav/schema.
Use the schema docs as the canonical reference for parameter locations, styles, body types, and serialization behavior.

Testing

# Run tests
go test ./...

# With race detector
go test -race ./...

# With coverage
go test -coverprofile=coverage.out ./...

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests: go test -race ./...
  5. Run linter: golangci-lint run
  6. Commit with clear messages
  7. Open a Pull Request

License

MIT License - see LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type API

type API struct {
	// Info contains API metadata (title, version, description, contact, license).
	Info model.Info

	// Servers lists available server URLs for the API.
	Servers []model.Server

	// Tags provides additional metadata for operations.
	Tags []model.Tag

	// SecuritySchemes defines available authentication/authorization schemes.
	SecuritySchemes map[string]*model.SecurityScheme

	// DefaultSecurity applies security requirements to all operations by default.
	DefaultSecurity []model.SecurityRequirement

	// ExternalDocs provides external documentation links.
	ExternalDocs *model.ExternalDocs

	// Extensions contains specification extensions (fields prefixed with x-).
	// Extensions are added to the root of the OpenAPI specification.
	//
	// Direct mutation of this map after New/MustNew bypasses API.Validate().
	// However, projection-time filtering via copyExtensions still applies:
	// - Keys must start with "x-"
	// - In OpenAPI 3.1.x, keys starting with "x-oai-" or "x-oas-" are reserved and will be filtered
	//
	// Prefer using WithExtension() option instead of direct mutation.
	Extensions map[string]any

	// Version is the target OpenAPI version.
	Version string

	// StrictDownlevel causes projection to error (instead of warn) when
	// 3.1-only features are used with a 3.0 target.
	// Default: false
	StrictDownlevel bool

	// ValidateSpec enables JSON Schema validation of generated specs.
	// When enabled, Generate validates the output against the official
	// OpenAPI meta-schema (3.0.x or 3.1.x based on target version).
	// This catches specification errors early but adds ~1-5ms overhead.
	// Default: false
	ValidateSpec bool

	// SchemaPrefix is the prefix for the OpenAPI schema.
	SchemaPrefix string

	// TagConfig configures struct tag names used for OpenAPI schema generation.
	// If not set, uses default tag names (schema, body, openapi, validate, default, requires).
	TagConfig config.TagConfig
	// contains filtered or unexported fields
}

API holds OpenAPI configuration and defines an API specification. All fields are public for functional options, but direct modification after creation is not recommended. Use functional options to configure.

Create instances using [New] or [MustNew].

func NewAPI

func NewAPI(opts ...Option) *API

NewAPI creates a new OpenAPI API.

Example:

api := openapi.NewAPI(
    openapi.WithInfoTitle("My API"),
    openapi.WithInfoVersion("1.0.0"),
    openapi.WithInfoDescription("API description"),
)

func (*API) Generate

func (a *API) Generate(ctx context.Context, ops ...Operation) (*Result, error)

Generate produces an OpenAPI specification from operations.

This is a pure function with no side effects. It takes configuration and operations as input and produces JSON/YAML bytes as output. Caching and state management are the caller's responsibility.

Example:

api := openapi.MustNew(
    openapi.WithTitle("My API", "1.0.0"),
    openapi.WithBearerAuth("bearerAuth", "JWT"),
)

result, err := api.Generate(ctx,
    openapi.GET("/users/:id",
        openapi.Summary("Get user"),
        openapi.Response(200, UserResponse{}),
    ),
    openapi.POST("/users",
        openapi.Summary("Create user"),
        openapi.Request(CreateUserRequest{}),
        openapi.Response(201, UserResponse{}),
    ),
)
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(result.JSON))

type OAuth2Flow

type OAuth2Flow struct {
	// Type specifies the OAuth2 flow type (implicit, password, clientCredentials, authorizationCode).
	Type OAuthFlowType

	// AuthorizationURL is required for implicit and authorizationCode flows.
	AuthorizationURL string

	// TokenURL is required for password, clientCredentials, and authorizationCode flows.
	TokenURL string

	// RefreshURL is optional for all flows.
	RefreshURL string

	// Scopes maps scope names to descriptions (required, can be empty).
	Scopes map[string]string
}

OAuth2Flow configures a single OAuth2 flow with explicit type.

type OAuthFlowType

type OAuthFlowType string

OAuthFlowType represents the type of OAuth2 flow.

const (
	// FlowImplicit represents the OAuth2 implicit flow.
	FlowImplicit OAuthFlowType = "implicit"
	// FlowPassword represents the OAuth2 resource owner password flow.
	FlowPassword OAuthFlowType = "password"
	// FlowClientCredentials represents the OAuth2 client credentials flow.
	FlowClientCredentials OAuthFlowType = "clientCredentials"
	// FlowAuthorizationCode represents the OAuth2 authorization code flow.
	FlowAuthorizationCode OAuthFlowType = "authorizationCode"
)

type Operation

type Operation struct {
	Method string // HTTP method (GET, POST, etc.)
	Path   string // URL path with parameters (e.g. "/users/:id")
	// contains filtered or unexported fields
}

Operation represents an OpenAPI operation (HTTP method + path + metadata). Create operations using the HTTP method constructors: GET, POST, PUT, PATCH, DELETE, etc.

func DELETE

func DELETE(path string, opts ...OperationDocOption) Operation

DELETE creates an Operation for a DELETE request.

Example:

openapi.DELETE("/users/:id",
    openapi.WithSummary("Delete user"),
    openapi.WithResponse(204, nil),
)

func GET

func GET(path string, opts ...OperationDocOption) Operation

GET creates an Operation for a GET request.

Example:

openapi.GET("/users/:id",
    openapi.WithSummary("Get user"),
    openapi.WithResponse(200, User{}),
)
func HEAD(path string, opts ...OperationDocOption) Operation

HEAD creates an Operation for a HEAD request.

Example:

openapi.HEAD("/users/:id",
    openapi.WithSummary("Check user exists"),
)

func OPTIONS

func OPTIONS(path string, opts ...OperationDocOption) Operation

OPTIONS creates an Operation for an OPTIONS request.

Example:

openapi.OPTIONS("/users",
    openapi.WithSummary("Get supported methods"),
)

func PATCH

func PATCH(path string, opts ...OperationDocOption) Operation

PATCH creates an Operation for a PATCH request.

Example:

openapi.PATCH("/users/:id",
    openapi.WithSummary("Partially update user"),
    openapi.WithRequest(PatchUserRequest{}),
    openapi.WithResponse(200, User{}),
)

func POST

func POST(path string, opts ...OperationDocOption) Operation

POST creates an Operation for a POST request.

Example:

openapi.POST("/users",
    openapi.WithSummary("Create user"),
    openapi.WithRequest(CreateUserRequest{}),
    openapi.WithResponse(201, User{}),
)

func PUT

func PUT(path string, opts ...OperationDocOption) Operation

PUT creates an Operation for a PUT request.

Example:

openapi.PUT("/users/:id",
    openapi.WithSummary("Update user"),
    openapi.WithRequest(UpdateUserRequest{}),
    openapi.WithResponse(200, User{}),
)

func TRACE

func TRACE(path string, opts ...OperationDocOption) Operation

TRACE creates an Operation for a TRACE request.

Example:

openapi.TRACE("/users/:id",
    openapi.WithSummary("Trace request"),
)

type OperationDocOption

type OperationDocOption func(*operationDoc)

OperationDocOption configures an OpenAPI operation. Use with HTTP method constructors like GET, POST, PUT, etc.

func WithConsumes

func WithConsumes(contentTypes ...string) OperationDocOption

WithConsumes sets the content types that this operation accepts.

Example:

openapi.POST("/users",
    openapi.WithConsumes("application/xml", "application/json"),
)

func WithDeprecated

func WithDeprecated() OperationDocOption

WithDeprecated marks the operation as deprecated.

Example:

openapi.GET("/old-endpoint",
    openapi.WithDeprecated(),
)

func WithDescription

func WithDescription(s string) OperationDocOption

WithDescription sets the operation description.

Example:

openapi.GET("/users/:id",
    openapi.WithDescription("Retrieves a user by their unique identifier"),
)

func WithOperationExtension

func WithOperationExtension(key string, value any) OperationDocOption

WithOperationExtension adds a specification extension to the operation.

Extension keys MUST start with "x-". In OpenAPI 3.1.x, keys starting with "x-oai-" or "x-oas-" are reserved for the OpenAPI Initiative.

Example:

openapi.GET("/users/:id",
    openapi.WithOperationExtension("x-rate-limit", 100),
    openapi.WithOperationExtension("x-internal", true),
)

func WithOperationID

func WithOperationID(id string) OperationDocOption

WithOperationID sets a custom operation ID.

Example:

openapi.GET("/users/:id",
    openapi.WithOperationID("getUserById"),
)

func WithOptions

func WithOptions(opts ...OperationDocOption) OperationDocOption

WithOptions composes multiple OperationDocOptions into a single option.

This enables creating reusable option sets for common patterns across operations. Options are applied in the order they are provided, with later options potentially overriding values set by earlier options.

Example:

// Define reusable option sets
var (
    CommonErrors = openapi.WithOptions(
        openapi.WithResponse(400, Error{}),
        openapi.WithResponse(401, Error{}),
        openapi.WithResponse(500, Error{}),
    )

    AuthRequired = openapi.WithOptions(
        openapi.WithSecurity("jwt"),
    )

    UserEndpoint = openapi.WithOptions(
        openapi.WithTags("users"),
        AuthRequired,
        CommonErrors,
    )
)

// Apply composed options to operations
openapi.GET("/users/:id",
    UserEndpoint,
    openapi.WithSummary("Get user"),
    openapi.WithResponse(200, User{}),
)

openapi.POST("/users",
    UserEndpoint,
    openapi.WithSummary("Create user"),
    openapi.WithRequest(CreateUser{}),
    openapi.WithResponse(201, User{}),
)

func WithProduces

func WithProduces(contentTypes ...string) OperationDocOption

WithProduces sets the content types that this operation returns.

Example:

openapi.GET("/users/:id",
    openapi.WithProduces("application/xml", "application/json"),
)

func WithRequest

func WithRequest(req any, examples ...example.Example) OperationDocOption

WithRequest sets the request type and optionally provides examples.

Example:

openapi.POST("/users",
    openapi.WithRequest(CreateUserRequest{}),
)

func WithResponse

func WithResponse(status int, resp any, examples ...example.Example) OperationDocOption

WithResponse sets the response schema and examples for a status code.

Example:

openapi.GET("/users/:id",
    openapi.WithResponse(200, User{}),
    openapi.WithResponse(404, ErrorResponse{}),
)

With named examples:

openapi.GET("/users/:id",
    openapi.WithResponse(200, User{},
        example.New("success", User{ID: 1, Name: "John"}),
        example.New("admin", User{ID: 2, Name: "Admin"},
            example.WithSummary("Admin user"),
            example.WithDescription("User with elevated permissions"),
        ),
    ),
)

func WithSecurity

func WithSecurity(scheme string, scopes ...string) OperationDocOption

WithSecurity adds a security requirement.

Example:

openapi.GET("/users/:id",
    openapi.WithSecurity("bearerAuth"),
)

openapi.POST("/users",
    openapi.WithSecurity("oauth2", "read:users", "write:users"),
)

func WithSummary

func WithSummary(s string) OperationDocOption

WithSummary sets the operation summary.

Example:

openapi.GET("/users/:id",
    openapi.WithSummary("Get user by ID"),
)

func WithTags

func WithTags(tags ...string) OperationDocOption

WithTags adds tags to the operation.

Example:

openapi.GET("/users/:id",
    openapi.WithTags("users", "authentication"),
)

type Option

type Option func(*API)

Option configures OpenAPI behavior using the functional options pattern. Options are applied in order, with later options potentially overriding earlier ones.

func WithAPIKey

func WithAPIKey(name, paramName string, in ParameterLocation, desc string) Option

WithAPIKey adds API key authentication scheme.

Parameters:

  • name: Scheme name used in security requirements
  • paramName: Name of the header/query parameter (e.g., "X-API-Key")
  • in: Location of the API key - use InHeader, InQuery, or InCookie
  • desc: Description shown in Swagger UI

Example:

openapi.WithAPIKey("apiKey", "X-API-Key", openapi.InHeader, "API key in X-API-Key header")

func WithBearerAuth

func WithBearerAuth(name, desc string) Option

WithBearerAuth adds Bearer (JWT) authentication scheme.

The name is used to reference this scheme in security requirements. The description appears in Swagger UI to help users understand the authentication.

Example:

openapi.WithBearerAuth("bearerAuth", "JWT token authentication. Format: Bearer <token>")

Then use in routes:

app.GET("/protected", handler).Bearer()

func WithContact

func WithContact(name, url, email string) Option

WithContact sets contact information for the API.

All parameters are optional. Empty strings are omitted from the specification.

Example:

openapi.WithContact("API Support", "https://example.com/support", "[email protected]")

func WithDefaultSecurity

func WithDefaultSecurity(scheme string, scopes ...string) Option

WithDefaultSecurity sets default security requirements applied to all operations.

Operations can override this by specifying their own security requirements using RouteWrapper.Security() or RouteWrapper.Bearer().

Example:

// Apply Bearer auth to all operations by default
openapi.WithDefaultSecurity("bearerAuth")

// Apply OAuth with specific scopes
openapi.WithDefaultSecurity("oauth2", "read", "write")

func WithExtension

func WithExtension(key string, value any) Option

WithExtension adds a specification extension to the root OpenAPI specification.

Extension keys MUST start with "x-". In OpenAPI 3.1.x, keys starting with "x-oai-" or "x-oas-" are reserved for the OpenAPI Initiative.

The value can be any valid JSON value (null, primitive, array, or object). Validation of extension keys happens during API.Validate().

Example:

openapi.WithExtension("x-internal-id", "api-v2")
openapi.WithExtension("x-code-samples", []map[string]any{
    {"lang": "curl", "source": "curl https://api.example.com/users"},
})

func WithExternalDocs

func WithExternalDocs(url, description string) Option

WithExternalDocs sets external documentation URL and optional description.

func WithInfoDescription

func WithInfoDescription(desc string) Option

WithInfoDescription sets the API description in the Info object.

The description supports Markdown formatting and appears in the OpenAPI spec and Swagger UI.

Example:

openapi.WithInfoDescription("A RESTful API for managing users and their profiles.")

func WithInfoExtension

func WithInfoExtension(key string, value any) Option

WithInfoExtension adds a specification extension to the Info object.

Extension keys must start with "x-". In OpenAPI 3.1.x, keys starting with "x-oai-" or "x-oas-" are reserved and cannot be used.

Example:

openapi.WithInfoExtension("x-api-category", "public")

func WithInfoSummary

func WithInfoSummary(summary string) Option

WithInfoSummary sets the API summary in the Info object (OpenAPI 3.1+ only). In 3.0 targets, this will be dropped with a warning.

Example:

openapi.WithInfoSummary("User Management API")

func WithInfoTitle

func WithInfoTitle(title string) Option

WithInfoTitle sets the API title.

Example:

openapi.WithInfoTitle("User Management API")

func WithInfoVersion

func WithInfoVersion(version string) Option

WithInfoVersion sets the API version.

Example:

openapi.WithInfoVersion("2.1.0")

func WithLicense

func WithLicense(name, url string) Option

WithLicense sets license information for the API using a URL (OpenAPI 3.0 style).

The name is required. URL is optional. This is mutually exclusive with identifier - use WithLicenseIdentifier for SPDX identifiers. Validation occurs when New() is called.

Example:

openapi.WithLicense("MIT", "https://opensource.org/licenses/MIT")

func WithLicenseIdentifier

func WithLicenseIdentifier(name, identifier string) Option

WithLicenseIdentifier sets license information for the API using an SPDX identifier (OpenAPI 3.1+).

The name is required. Identifier is an SPDX license expression (e.g., "Apache-2.0"). This is mutually exclusive with URL - use WithLicense for URL-based licenses. Validation occurs when New() is called.

Example:

openapi.WithLicenseIdentifier("Apache 2.0", "Apache-2.0")

func WithOAuth2

func WithOAuth2(name, desc string, flows ...OAuth2Flow) Option

WithOAuth2 adds OAuth2 authentication scheme.

At least one flow must be configured. Use OAuth2Flow to configure each flow type. Multiple flows can be provided to support different OAuth2 flow types.

Example:

openapi.WithOAuth2("oauth2", "OAuth2 authentication",
	openapi.OAuth2Flow{
		Type:             openapi.FlowAuthorizationCode,
		AuthorizationURL: "https://example.com/oauth/authorize",
		TokenURL:         "https://example.com/oauth/token",
		Scopes: map[string]string{
			"read":  "Read access",
			"write": "Write access",
		},
	},
	openapi.OAuth2Flow{
		Type:     openapi.FlowClientCredentials,
		TokenUrl: "https://example.com/oauth/token",
		Scopes:   map[string]string{"read": "Read access"},
	},
)

func WithOpenIDConnect

func WithOpenIDConnect(name, url, desc string) Option

WithOpenIDConnect adds OpenID Connect authentication scheme.

Parameters:

  • name: Scheme name used in security requirements
  • url: Well-known URL to discover OpenID Connect provider metadata
  • desc: Description shown in Swagger UI

Example:

openapi.WithOpenIDConnect("oidc", "https://example.com/.well-known/openid-configuration", "OpenID Connect authentication")

func WithSchemaPrefix

func WithSchemaPrefix(prefix string) Option

WithSchemaPrefix sets the prefix for OpenAPI schema references. The prefix is used when generating $ref references to schemas in components/schemas.

Default: "#/components/schemas/"

Example:

openapi.WithSchemaPrefix("#/definitions/")

func WithServer

func WithServer(url string, opts ...ServerOption) Option

WithServer adds a server URL to the specification.

Multiple servers can be added by calling this option multiple times. Use server options to configure description, variables, and extensions.

Example:

openapi.WithServer("https://api.example.com",
    openapi.WithServerDescription("Production"),
),
openapi.WithServer("https://{env}.example.com",
    openapi.WithServerDescription("Multi-tenant API"),
    openapi.WithServerVariable("env", "prod", []string{"prod", "staging"}, "Environment"),
    openapi.WithServerExtension("x-region", "us-east-1"),
),

func WithStrictDownlevel

func WithStrictDownlevel(strict bool) Option

WithStrictDownlevel causes projection to error (instead of warn) when 3.1-only features are used with a 3.0 target.

Default: false (warnings only)

Example:

openapi.WithStrictDownlevel(true)

func WithTag

func WithTag(name, desc string) Option

WithTag adds a tag to the specification.

Tags are used to group operations in Swagger UI. Operations can be assigned tags using RouteWrapper.Tags(). Multiple tags can be added by calling this option multiple times.

Example:

openapi.WithTag("users", "User management operations"),
openapi.WithTag("orders", "Order processing operations"),

func WithTagConfig

func WithTagConfig(cfg config.TagConfig) Option

WithTagConfig configures struct tag names used for OpenAPI schema generation.

By default, the following tag names are used:

  • schema: for parameter location/style metadata
  • body: for request/response body metadata
  • openapi: for OpenAPI-specific metadata
  • validate: for validation constraints
  • default: for default values
  • requires: for dependent required fields

Use this option to customize tag names for compatibility with other libraries or to match your existing codebase conventions.

Partial configurations are supported - only provide the tag names you want to customize. Unspecified tags will use their defaults.

Example:

import "github.com/talav/openapi/config"

// Customize only specific tags - others use defaults
openapi.NewAPI(
    openapi.WithTagConfig(config.TagConfig{
        Schema:   "param",  // Custom
        OpenAPI:  "api",    // Custom
        Validate: "rules",  // Custom
        // Body, Default, Requires will use defaults ("body", "default", "requires")
    }),
)

func WithTermsOfService

func WithTermsOfService(url string) Option

WithTermsOfService sets the Terms of Service URL/URI.

func WithValidation

func WithValidation(enabled bool) Option

WithValidation enables or disables JSON Schema validation of the generated OpenAPI spec.

When enabled, Generate() validates the output against the official OpenAPI meta-schema and returns an error if the spec is invalid.

This is useful for:

  • Development: Catch spec generation bugs early
  • CI/CD: Ensure generated specs are valid before deployment
  • Testing: Verify spec correctness in tests

Performance: Adds ~1-5ms overhead per generation. The default is false for backward compatibility. Enable for development and testing to catch errors early.

Default: false

Example:

openapi.WithValidation(false) // Disable for performance

func WithVersion

func WithVersion(version string) Option

WithVersion sets the target OpenAPI version.

Example:

openapi.WithVersion("3.1.2")

type ParameterLocation

type ParameterLocation string

ParameterLocation represents where an API parameter can be located.

const (
	// InHeader indicates the parameter is passed in the HTTP header.
	InHeader ParameterLocation = "header"

	// InQuery indicates the parameter is passed as a query string parameter.
	InQuery ParameterLocation = "query"

	// InCookie indicates the parameter is passed as a cookie.
	InCookie ParameterLocation = "cookie"
)

type Result

type Result struct {
	JSON []byte

	// Warnings contains informational, non-fatal issues.
	// These are advisory only and do not indicate failure.
	Warnings debug.Warnings
}

type SecurityReq

type SecurityReq struct {
	Scheme string
	Scopes []string
}

SecurityReq represents a security requirement for an operation.

type ServerOption

type ServerOption func(*model.Server)

ServerOption configures a Server using the functional options pattern.

func WithServerDescription

func WithServerDescription(desc string) ServerOption

WithServerDescription sets the server description.

Example:

openapi.WithServer("https://api.example.com",
    openapi.WithServerDescription("Production environment"),
),

func WithServerExtension

func WithServerExtension(key string, value any) ServerOption

WithServerExtension adds a specification extension to the server.

Extension keys MUST start with "x-". In OpenAPI 3.1.x, keys starting with "x-oai-" or "x-oas-" are reserved for the OpenAPI Initiative.

Example:

openapi.WithServer("https://api.example.com",
    openapi.WithServerExtension("x-region", "us-east-1"),
    openapi.WithServerExtension("x-deployment", "production"),
),

func WithServerVariable

func WithServerVariable(name, defaultValue string, enum []string, description string) ServerOption

WithServerVariable adds a variable to the server URL template.

The variable name should match a placeholder in the server URL (e.g., {username}). Default is required. Enum and description are optional.

Example:

openapi.WithServer("https://{username}.example.com:{port}/v1",
    openapi.WithServerVariable("username", "demo", []string{"demo", "prod"}, "User subdomain"),
    openapi.WithServerVariable("port", "8443", []string{"8443", "443"}, "Server port"),
),

Directories

Path Synopsis
Package example provides OpenAPI Example Object support.
Package example provides OpenAPI Example Object support.
internal
metadata
Package metadata extracts OpenAPI schema metadata from Go struct field tags.
Package metadata extracts OpenAPI schema metadata from Go struct field tags.

Jump to

Keyboard shortcuts

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