config

package
v2.1.93 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultHistoryURL      = "/.history"
	DefaultHistoryDuration = 60 * time.Minute
)
View Source
const DefaultReplayTTL = 24 * time.Hour

DefaultReplayTTL is the default time-to-live for replay recordings.

View Source
const (
	DefaultUpstreamTimeout = 5 * time.Second
)

DefaultUpstreamTimeout defaults.

Variables

View Source
var DefaultFailOnStatus = HTTPStatusMatchConfig{
	{Range: "400-499", Except: []int{401, 403}},
}

DefaultFailOnStatus is the default fail-on config applied when FailOn is nil. Most 4xx errors indicate client-side problems that the generator cannot fix. 401/403 are excluded because they typically indicate missing/invalid credentials in the proxy setup, not a real client error.

Functions

func ExtractPathValues

func ExtractPathValues(requestPath, pattern string) map[string]string

ExtractPathValues aligns segments of a request path against a pattern and returns a map of path variable names to their actual values. Returns nil if paths don't align.

Types

type AppConfig

type AppConfig struct {
	Title       string `yaml:"title"`
	Port        int    `yaml:"port"`
	BaseURL     string `yaml:"baseURL" env:"APP_BASE_URL"`
	InternalURL string `yaml:"internalURL" env:"APP_INTERNAL_URL"`
	HomeURL     string `yaml:"homeURL"`
	ServiceURL  string `yaml:"serviceURL" env:"APP_SERVICE_URL"`

	// AssetsURL is the base URL for static UI assets (CSS, JS, images, icons).
	// Empty means assets are served with relative paths (default).
	AssetsURL string `yaml:"assetsURL" env:"APP_ASSETS_URL"`

	ContextAreaPrefix string            `yaml:"contextAreaPrefix"`
	DisableUI         bool              `yaml:"disableUI"`
	Paths             Paths             `yaml:"-"`
	Editor            *EditorConfig     `yaml:"editor"`
	History           *AppHistoryConfig `yaml:"history"`
	Storage           *StorageConfig    `yaml:"storage"`
	Extra             map[string]any    `yaml:"extra"`
}

AppConfig is the app configuration.

func NewAppConfigFromBytes

func NewAppConfigFromBytes(bts []byte, baseDir string) (*AppConfig, error)

NewAppConfigFromBytes creates an AppConfig from YAML bytes, filling missing values with defaults. Environment variables override YAML values when set (via `env` struct tags).

func NewDefaultAppConfig

func NewDefaultAppConfig(baseDir string) *AppConfig

NewDefaultAppConfig creates a new default app config in case the config file is missing, not found or any other error.

type AppHistoryConfig added in v2.1.76

type AppHistoryConfig struct {
	Enabled  *bool         `yaml:"enabled"`
	URL      string        `yaml:"url"`
	Duration time.Duration `yaml:"duration" env:"ROUTER_HISTORY_DURATION"`
}

AppHistoryConfig configures request/response history at the application level.

func NewDefaultAppHistoryConfig added in v2.1.76

func NewDefaultAppHistoryConfig() *AppHistoryConfig

NewDefaultAppHistoryConfig creates the default history config.

type BodyMatchCondition added in v2.1.93

type BodyMatchCondition struct {
	Path   string      `yaml:"path"`
	Equals interface{} `yaml:"equals"`
}

type BodyMatchConfig added in v2.1.93

type BodyMatchConfig struct {
	Default string               `yaml:"default"`
	Fail    []BodyMatchCondition `yaml:"fail"`
	Except  []BodyMatchCondition `yaml:"except"`
}

type CacheConfig

type CacheConfig struct {
	Requests bool          `yaml:"requests"`
	Replay   *ReplayConfig `yaml:"replay,omitempty"`
}

CacheConfig defines the cache configuration for a service. Requests is a flag whether to cache GET requests. Replay is the replay configuration for recording and replaying API responses.

func NewCacheConfig

func NewCacheConfig() *CacheConfig

NewCacheConfig creates a new CacheConfig with default values.

type EditorConfig

type EditorConfig struct {
	Theme     string `yaml:"theme"`
	DarkTheme string `yaml:"darkTheme"`
	FontSize  int    `yaml:"fontSize"`
}

type HTTPStatusConfig

type HTTPStatusConfig struct {
	Exact  int              `yaml:"exact"`
	Range  string           `yaml:"range"`
	Except []int            `yaml:"except"`
	Body   *BodyMatchConfig `yaml:"body"`
}

func (*HTTPStatusConfig) Is

func (s *HTTPStatusConfig) Is(status int, body string) bool

type HTTPStatusMatchConfig

type HTTPStatusMatchConfig []HTTPStatusConfig

func (HTTPStatusMatchConfig) Is

func (ss HTTPStatusMatchConfig) Is(status int, body string) bool

type HandlerConfig

type HandlerConfig struct {
	SelfPrefix string `yaml:"self-prefix"`
}

HandlerConfig is a config for the handler. It is created from the service config. SelfPrefix is the prefix for helper routes outside OpenAPI spec:

for example, payload generation.

func NewHandlerConfig

func NewHandlerConfig(service *ServiceConfig) *HandlerConfig

NewHandlerConfig creates a new handler config from the service config.

type HistoryConfig added in v2.1.71

type HistoryConfig struct {
	Enabled     *bool    `yaml:"enabled,omitempty"`
	MaskHeaders []string `yaml:"mask-headers,omitempty"`
}

HistoryConfig controls request/response history recording for a service.

Enabled toggles recording on or off (defaults to true when nil). MaskHeaders lists header names whose values should be masked before saving, showing only the last 4 characters (matched case-insensitively).

Example YAML:

history:
  enabled: true
  mask-headers:
    - Authorization
    - X-Api-Key

Shorthand to disable history entirely:

history:
  enabled: false

func NewHistoryConfig added in v2.1.71

func NewHistoryConfig() *HistoryConfig

NewHistoryConfig creates a HistoryConfig with defaults: enabled, common sensitive headers masked.

func (*HistoryConfig) UnmarshalYAML added in v2.1.71

func (h *HistoryConfig) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML supports both boolean shorthand and object forms:

history: false        # shorthand to disable
history:              # full form
  enabled: true
  mask-headers: [Authorization]

type KeyValue

type KeyValue[K, V any] struct {
	Key   K
	Value V
}

type OptionalProperties

type OptionalProperties struct {
	Min int `yaml:"min"`
	Max int `yaml:"max"`
}

OptionalProperties controls how many optional properties to keep in generated types. This helps reduce the size of generated code for schemas with many optional fields.

Min and Max specify the range of optional properties to keep:

  • If Min == Max, keeps exactly that many optional properties
  • If Min < Max, keeps a random number between Min and Max (inclusive)

When nil (not set in config), all optional properties are kept.

type Paths

type Paths struct {
	Base      string
	Docs      string
	Resources string
	Data      string
	OpenAPI   string
	Static    string
	Services  string
	UI        string
}

Paths is a struct that holds all the paths used by the application.

func NewPaths

func NewPaths(baseDir string) Paths

type RedisConfig

type RedisConfig struct {
	// host:port address. When Host is set via env, Address is built from Host:Port.
	Address  string `yaml:"address"`
	Host     string `yaml:"host" env:"REDIS_HOST"`
	Port     string `yaml:"port" env:"REDIS_PORT" envDefault:"6379"`
	Username string `yaml:"username" env:"REDIS_USERNAME"`
	Password string `yaml:"password" env:"REDIS_PASSWORD"`
	DB       int    `yaml:"db" env:"REDIS_DB"`
	TLS      bool   `yaml:"tls" env:"REDIS_TLS"`
}

RedisConfig configures Redis connection.

func (*RedisConfig) GetAddress

func (r *RedisConfig) GetAddress() string

GetAddress returns the Redis address. If Host is set, it takes precedence over Address.

type ReplayConfig

type ReplayConfig struct {
	// TTL is how long recordings are kept. Default: 24h.
	TTL time.Duration `yaml:"ttl"`

	// UpstreamOnly when true only records responses from upstream services.
	UpstreamOnly bool `yaml:"upstream-only"`

	// AutoReplay when true activates replay for configured endpoints without requiring
	// the X-Cxs-Replay header. When false (default), the header must be present.
	AutoReplay bool `yaml:"auto-replay"`

	// Endpoints maps path patterns to their match configurations.
	// Two forms are supported:
	//
	//   With method (matches only that method):
	//     /pay:
	//       POST:
	//         match: [reference]
	//
	//   Without method (matches any request method):
	//     /pay:
	//       match: [reference]
	Endpoints map[string]map[string]*ReplayEndpoint `yaml:"endpoints"`
}

ReplayConfig defines the replay (VCR-like) configuration for recording and replaying API responses based on request body content.

Replay is activated either by the X-Cxs-Replay header or by setting AutoReplay to true. When a request comes in, specified fields are extracted from the request body, a content-addressed key is built, and a stored recording is returned if one exists. If no recording exists, the response from downstream is captured and stored.

Example YAML:

cache:
  replay:
    ttl: 24h
    auto-replay: true
    upstream-only: false
    endpoints:
      /foo/{f-id}/bar/{b-id}:
        POST:
          match:
            body:
              - data.name
              - data.address.zip

func (*ReplayConfig) GetEndpoint

func (rc *ReplayConfig) GetEndpoint(requestPath, method string) (string, *ReplayEndpoint)

GetEndpoint finds the matching endpoint config for a request path and method. Returns the pattern path (for key building) and the endpoint config.

Three config forms are supported:

  • Path only ("/pay:") - matches any method, no match fields
  • Path + method ("/pay: POST:") - matches that method, no match fields
  • Path + method + match ("/pay: POST: match: [...]") - full config

Returns "", nil if no match is found.

func (*ReplayConfig) WithDefaults

func (rc *ReplayConfig) WithDefaults() *ReplayConfig

WithDefaults fills zero-valued fields with defaults.

type ReplayEndpoint

type ReplayEndpoint struct {
	// Match specifies which request fields form the replay key.
	Match *ReplayMatch `yaml:"match"`
}

ReplayEndpoint defines the match configuration for a specific endpoint and HTTP method.

type ReplayMatch

type ReplayMatch struct {
	// Path fields are path variable names to include in the replay key.
	Path []string `yaml:"path"`

	// Body fields are extracted from the request body (JSON dotted paths or form-encoded flat keys).
	Body []string `yaml:"body"`

	// Query fields are extracted from the URL query string.
	Query []string `yaml:"query"`
}

ReplayMatch specifies where to extract match field values from.

func (*ReplayMatch) AllFields

func (rm *ReplayMatch) AllFields() []string

AllFields returns all match field names (path + body + query) for key building.

type ServiceConfig

type ServiceConfig struct {
	Name            string                   `yaml:"name,omitempty"`
	Upstream        *UpstreamConfig          `yaml:"upstream,omitempty"`
	Latency         time.Duration            `yaml:"latency,omitempty"`
	Latencies       map[string]time.Duration `yaml:"latencies,omitempty"`
	Errors          map[string]int           `yaml:"errors,omitempty"`
	Cache           *CacheConfig             `yaml:"cache,omitempty"`
	History         *HistoryConfig           `yaml:"history,omitempty"`
	ResourcesPrefix string                   `yaml:"resources-prefix,omitempty"`
	SpecOptions     *SpecOptions             `yaml:"spec,omitempty"`
	Extra           map[string]any           `yaml:"extra,omitempty"`
	// contains filtered or unexported fields
}

ServiceConfig defines the configuration for a service. Name is the optional name of the service. Upstream is the upstream configuration. Latency is the default latency for the service. Latencies is a map of percentiles to latencies. Errors is a map of percentiles to error codes. Validate is the validation configuration. Cache is the cache configuration. ResourcesPrefix is the prefix for helper routes outside OpenAPI spec. SpecOptions allows OpenAPI spec simplifications for code generation.

func NewServiceConfig

func NewServiceConfig() *ServiceConfig

NewServiceConfig creates a new ServiceConfig with default values.

func NewServiceConfigFromBytes

func NewServiceConfigFromBytes(bts []byte) (*ServiceConfig, error)

func (*ServiceConfig) GetError

func (s *ServiceConfig) GetError() int

GetError returns the error based on the percentiles:

random number is generated between 1 and 100 to simulate the percentile.

If no errors are defined, it returns 0.

func (*ServiceConfig) GetLatency

func (s *ServiceConfig) GetLatency() time.Duration

GetLatency returns the latency.

func (*ServiceConfig) HistoryEnabled

func (s *ServiceConfig) HistoryEnabled() bool

HistoryEnabled returns whether request history recording is enabled. Defaults to true when not explicitly set.

func (*ServiceConfig) OverwriteWith

func (s *ServiceConfig) OverwriteWith(other *ServiceConfig) *ServiceConfig

OverwriteWith overwrites fields in s with non-nil/non-empty values from other. This is useful for merging configurations where other takes precedence.

func (*ServiceConfig) WithDefaults

func (s *ServiceConfig) WithDefaults() *ServiceConfig

WithDefaults fills nil properties with default values from NewServiceConfig.

type SpecOptions

type SpecOptions struct {
	LazyLoad           bool                `yaml:"lazyLoad"`
	Simplify           bool                `yaml:"simplify"`
	OptionalProperties *OptionalProperties `yaml:"optional-properties"`
}

SpecOptions allows OpenAPI spec simplifications for code generation. These simplifications are particularly helpful for enormous schemas that would otherwise generate unwieldy code.

Simplifications include:

  • Removal of extra union elements (anyOf/oneOf/allOf)
  • Optionally limiting the number of optional properties kept

LazyLoad enables on-demand parsing of operations. When true, operations are parsed only when first accessed and cached for subsequent requests. This significantly speeds up server startup for large specs (e.g., Stripe with 500+ endpoints).

OptionalProperties is nil by default, meaning all optional properties are kept. Set it explicitly to limit the number of optional properties.

Example usage in YAML:

spec:
  lazyLoad: true    # Parse operations on-demand instead of at startup
  simplify: true
  optional-properties:
    min: 5        # Keep exactly 5 optional properties (when min == max)
    max: 5
    # OR
    min: 2        # Keep random number between 2-8 optional properties
    max: 8

func NewSpecOptions

func NewSpecOptions() *SpecOptions

type StorageConfig

type StorageConfig struct {
	Type         StorageType    `yaml:"type" env:"STORAGE_TYPE"`
	DriverConfig map[string]any `yaml:"-"`

	// Redis is kept for backward compatibility with env tags (REDIS_HOST, etc.).
	Redis *RedisConfig `yaml:"redis"`
}

StorageConfig configures shared storage for distributed features.

Each driver's options live under a YAML key matching the type name:

storage:
  type: redis
  redis:
    address: localhost:6379

DriverConfig is populated automatically from the matching section.

func (*StorageConfig) DriverOptions added in v2.1.91

func (c *StorageConfig) DriverOptions() map[string]any

DriverOptions returns the driver-specific config map. It prefers DriverConfig (extracted from the type-named YAML section). Falls back to converting the typed Redis config for backward compatibility.

type StorageType

type StorageType string

StorageType defines the type of storage backend.

const (
	// StorageTypeMemory is the default in-memory storage (per-instance).
	StorageTypeMemory StorageType = "memory"

	// StorageTypeRedis uses Redis for distributed storage.
	StorageTypeRedis StorageType = "redis"
)

type UpstreamConfig

type UpstreamConfig struct {
	URL     string            `yaml:"url"`
	Timeout time.Duration     `yaml:"timeout"`
	Headers map[string]string `yaml:"headers"`

	// FailOn defines which upstream HTTP status codes should be returned immediately
	// to the client without falling back to the generator.
	// nil (omitted): uses default (400-499 except 401, 403). Set to empty list (fail-on: []) to disable.
	FailOn *HTTPStatusMatchConfig `yaml:"fail-on"`

	// StickyTimeout enables server-side session affinity for upstream/generator routing.
	// When a client gets a generated (fallback) response, subsequent requests from the
	// same remote address skip upstream for this duration. 0 or omitted = disabled.
	StickyTimeout time.Duration `yaml:"sticky-timeout"`
}

Jump to

Keyboard shortcuts

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