traefik

package
v0.2.6 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: Apache-2.0 Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package traefik generates Traefik's dynamic configuration (§5.7). Traefik polls it through its HTTP provider; users never write Traefik config.

Index

Constants

View Source
const (
	ProbeHeader = "X-Syncloud-Probe"
	ProbeSuffix = "_probe"
)

The uptime monitor marks its probes with ProbeHeader. They reach the app through a router and Traefik service named after the route plus ProbeSuffix, whose metrics and access lines are left out of traffic (port names and domain IDs never contain "_", so no route can collide).

View Source
const AgentRouteName = "syncloud-agent"

AgentRouteName is the TCP route that passes agent.<domain>:443 to the agent gateway.

View Source
const DefaultDialTimeout = "2s"

DefaultDialTimeout bounds connecting to a task (over the private network).

View Source
const (

	// DevRegistryHost is the registry's hostname before a base domain exists.
	DevRegistryHost = "registry.localhost"
)
View Source
const SettingCustom = "traefik.custom"

SettingCustom holds the custom configuration as YAML.

View Source
const SettingGlobal = "traefik.settings"

SettingGlobal holds the global Traefik settings as JSON.

Variables

View Source
var MiddlewareKinds = []string{
	"addPrefix", "basicAuth", "buffering", "chain", "circuitBreaker", "compress", "contentType", "digestAuth", "errors",
	"forwardAuth", "grpcWeb", "headers", "ipAllowList", "inFlightReq", "passTLSClientCert", "rateLimit", "redirectRegex",
	"redirectScheme", "replacePath", "replacePathRegex", "retry", "stripPrefix", "stripPrefixRegex",
}

MiddlewareKinds are Traefik's HTTP middleware types.

View Source
var PresetTypes = []string{
	"ip-allowlist", "rate-limit", "basic-auth", "redirect-www", "cors", "security-headers", "circuit-breaker", "compress", "retry",
}

Middleware presets (§5.7): the toggles users attach to services, rendered into Traefik middlewares. A route applies them in a fixed order, so access checks run before anything else.

Functions

func Entrypoints

func Entrypoints(addrs map[string]string) []string

Entrypoints are the flags of extra TCP entrypoints (name -> address), sorted by name: the public database endpoints (Phase 12e).

func IsProbe added in v0.1.4

func IsProbe(name string) bool

IsProbe reports whether a Traefik router or service name ("svc-…_probe@http") is an uptime probe twin.

func MergeCustom

func MergeCustom(out, custom map[string]any)

MergeCustom adds custom routers, services, middlewares and transports (validated not to collide with generated names) to a configuration.

func MiddlewareName

func MiddlewareName(id string) string

MiddlewareName is a preset's Traefik name.

func PresetOrder

func PresetOrder(typ string) int

PresetOrder sorts attached presets the way a route applies them.

func PublicPreset

func PublicPreset(typ string, raw json.RawMessage) json.RawMessage

PublicPreset strips secrets (password hashes) from a stored config.

func ValidateCustom

func ValidateCustom(text string, gen map[string]any) (map[string]any, error)

ValidateCustom parses and checks custom YAML against the generated configuration gen (as served, without custom parts). It returns the configuration to merge.

func ValidatePreset

func ValidatePreset(typ string, raw, prev json.RawMessage) (json.RawMessage, error)

ValidatePreset checks and normalizes a preset's config. For basic-auth, new passwords are hashed, and a user given without a password keeps the hash from prev (the stored config being replaced).

func WithStatic

func WithStatic(base []string, s Settings) []string

WithStatic replaces the "--log.level" flag of base flags and appends the other static flags.

Types

type BasicAuth

type BasicAuth struct {
	Users        []string `json:"users"`
	Realm        string   `json:"realm,omitempty"`
	RemoveHeader bool     `json:"removeHeader"`
}

type Buffering

type Buffering struct {
	MaxRequestBodyBytes int64 `json:"maxRequestBodyBytes"`
}

Buffering limits request bodies.

type Certificate

type Certificate struct {
	CertFile string `json:"certFile"`
	KeyFile  string `json:"keyFile"`
}

Certificate holds PEM content inline (Traefik accepts content or a path).

type CircuitBreaker

type CircuitBreaker struct {
	Expression string `json:"expression"`
}

type Compress

type Compress struct{}

type Dynamic

type Dynamic struct {
	HTTP HTTPConfig `json:"http"`
	TCP  *TCPConfig `json:"tcp,omitempty"`
	UDP  *UDPConfig `json:"udp,omitempty"`
	TLS  *TLSConfig `json:"tls,omitempty"`
}

Dynamic is the subset of Traefik's dynamic configuration we generate.

type Extras

type Extras struct {
	// contains filtered or unexported fields
}

Extras caches what the database adds to the generated configuration: middleware presets with their attachments, and the custom configuration.

func NewExtras

func NewExtras(st *store.Store, log *slog.Logger) *Extras

func (*Extras) Chain

func (e *Extras) Chain(serviceID string) ([]string, bool)

Chain returns a service's middlewares and whether one replaces the default retry.

func (*Extras) Custom

func (e *Extras) Custom() map[string]any

Custom returns the custom configuration to merge.

func (*Extras) CustomText

func (e *Extras) CustomText() string

CustomText returns the stored YAML.

func (*Extras) Definitions

func (e *Extras) Definitions() map[string]Middleware

Definitions returns the preset middlewares.

func (*Extras) Reload

func (e *Extras) Reload(ctx context.Context) error

Reload reads presets and the custom configuration again.

func (*Extras) Settings

func (e *Extras) Settings() Settings

Settings returns the global settings.

type HTTPConfig

type HTTPConfig struct {
	Routers     map[string]Router     `json:"routers"`
	Services    map[string]Service    `json:"services"`
	Middlewares map[string]Middleware `json:"middlewares,omitempty"`
}

type Headers

type Headers struct {
	STSSeconds                    int      `json:"stsSeconds,omitempty"`
	STSIncludeSubdomains          bool     `json:"stsIncludeSubdomains,omitempty"`
	FrameDeny                     bool     `json:"frameDeny,omitempty"`
	ContentTypeNosniff            bool     `json:"contentTypeNosniff,omitempty"`
	BrowserXSSFilter              bool     `json:"browserXssFilter,omitempty"`
	ReferrerPolicy                string   `json:"referrerPolicy,omitempty"`
	AccessControlAllowOriginList  []string `json:"accessControlAllowOriginList,omitempty"`
	AccessControlAllowMethods     []string `json:"accessControlAllowMethods,omitempty"`
	AccessControlAllowHeaders     []string `json:"accessControlAllowHeaders,omitempty"`
	AccessControlAllowCredentials bool     `json:"accessControlAllowCredentials,omitempty"`
	AccessControlMaxAge           int      `json:"accessControlMaxAge,omitempty"`
	AddVaryHeader                 bool     `json:"addVaryHeader,omitempty"`
}

type HealthCheck

type HealthCheck struct {
	Path     string `json:"path"`
	Interval string `json:"interval"`
	Timeout  string `json:"timeout"`
}

HealthCheck is Traefik's active check of each server.

type IPAllowList

type IPAllowList struct {
	SourceRange []string `json:"sourceRange"`
}

type LoadBalancer

type LoadBalancer struct {
	Servers        []Server     `json:"servers"`
	PassHostHeader bool         `json:"passHostHeader"`
	HealthCheck    *HealthCheck `json:"healthCheck,omitempty"`
}

type Middleware

type Middleware struct {
	StripPrefix    *StripPrefix    `json:"stripPrefix,omitempty"`
	RedirectScheme *RedirectScheme `json:"redirectScheme,omitempty"`
	RedirectRegex  *RedirectRegex  `json:"redirectRegex,omitempty"`
	Retry          *Retry          `json:"retry,omitempty"`
	RateLimit      *RateLimit      `json:"rateLimit,omitempty"`
	BasicAuth      *BasicAuth      `json:"basicAuth,omitempty"`
	IPAllowList    *IPAllowList    `json:"ipAllowList,omitempty"`
	Headers        *Headers        `json:"headers,omitempty"`
	Compress       *Compress       `json:"compress,omitempty"`
	CircuitBreaker *CircuitBreaker `json:"circuitBreaker,omitempty"`
	Buffering      *Buffering      `json:"buffering,omitempty"`
}

func RenderPreset

func RenderPreset(typ string, raw json.RawMessage) (Middleware, error)

RenderPreset builds the Traefik middleware for a stored preset.

type Provider

type Provider struct {
	// Token must be presented in TokenHeader (the config carries TLS keys).
	Token       string
	TokenHeader string
	// ControllerURL is where Traefik reaches the controller.
	ControllerURL string
	// RegistryURL is where Traefik reaches the registry ("" disables its route).
	RegistryURL string
	// BaseDomain returns the current base domain ("" until one is set, §5.0.2).
	BaseDomain func() string
	// HTTPSPort is the public HTTPS port when it is not 443 (development).
	HTTPSPort string
	// Certificates returns the TLS certificates to serve.
	Certificates func() []Certificate
	// DefaultCertificate is served when no other certificate matches the
	// SNI, or there is none (nil: Traefik's self-signed one).
	DefaultCertificate func() *Certificate
	// ServiceRoutes returns the routes of user services.
	ServiceRoutes func() []ServiceRoute
	// Middlewares returns the preset middlewares routes refer to.
	Middlewares func() map[string]Middleware
	// Custom returns the validated raw configuration merged into the
	// generated one ("Advanced", §5.7).
	Custom func() map[string]any
	// MeshControllerURL is the controller as edge nodes reach it over the
	// private network (§8.5).
	MeshControllerURL func() string
	// Settings returns the global settings (nil: the defaults).
	Settings func() Settings
	// TCPRoutes returns the public database endpoints (only served with a
	// base domain: they need certificates) and public TCP ports of services.
	TCPRoutes func() []TCPRoute
	// UDPRoutes returns public UDP ports of services.
	UDPRoutes func() []UDPRoute
	// GitHost returns the built-in Git server's hostname ("" when it is
	// off, §5.8); GitServerURL is where Traefik reaches it.
	GitHost      func() string
	GitServerURL string
	// ProbeToken, when set, gives every service route a twin for the
	// uptime monitor's probes (requests carrying ProbeHeader with this
	// value), so its checks never count as the service's traffic.
	ProbeToken string
}

Provider serves the dynamic config to Traefik.

func (*Provider) Config

func (p *Provider) Config() Dynamic

Config builds the current dynamic configuration.

func (*Provider) EdgeConfig

func (p *Provider) EdgeConfig() map[string]any

EdgeConfig is the configuration for an edge node's Traefik (§8.5): the same routes and certificates, with the controller reached over the private network; the registry stays on the controller's own Traefik.

func (*Provider) Generated

func (p *Provider) Generated() map[string]any

Generated is the configuration without the custom part, as a map.

func (*Provider) Merged

func (p *Provider) Merged() map[string]any

Merged is the generated configuration with the custom one added.

func (*Provider) Redacted

func (p *Provider) Redacted() map[string]any

Redacted is the served configuration for display: certificates and keys are replaced by their sizes.

func (*Provider) ServeHTTP

func (p *Provider) ServeHTTP(w http.ResponseWriter, r *http.Request)

type ProxyProtocol added in v0.2.2

type ProxyProtocol struct {
	Version int `json:"version"`
}

ProxyProtocol makes Traefik send the client's address first (PROXY protocol).

type RateLimit

type RateLimit struct {
	Average         int              `json:"average"`
	Burst           int              `json:"burst"`
	Period          string           `json:"period,omitempty"`
	SourceCriterion *SourceCriterion `json:"sourceCriterion,omitempty"`
}

type RedirectRegex

type RedirectRegex struct {
	Regex       string `json:"regex"`
	Replacement string `json:"replacement"`
	Permanent   bool   `json:"permanent"`
}

type RedirectScheme

type RedirectScheme struct {
	Scheme    string `json:"scheme"`
	Port      string `json:"port,omitempty"`
	Permanent bool   `json:"permanent"`
}

type Retry

type Retry struct {
	Attempts        int    `json:"attempts"`
	InitialInterval string `json:"initialInterval,omitempty"`
}

type Router

type Router struct {
	Rule        string     `json:"rule"`
	Priority    int        `json:"priority,omitempty"`
	EntryPoints []string   `json:"entryPoints"`
	Middlewares []string   `json:"middlewares,omitempty"`
	Service     string     `json:"service"`
	TLS         *RouterTLS `json:"tls,omitempty"`
}

type RouterTLS

type RouterTLS struct {
	Passthrough bool `json:"passthrough,omitempty"`
}

type Server

type Server struct {
	URL string `json:"url"`
}

type Service

type Service struct {
	LoadBalancer LoadBalancer `json:"loadBalancer"`
}

type ServiceRoute

type ServiceRoute struct {
	Name    string
	Host    string
	Servers []string
	// Middlewares are attached presets, in the order to apply them. With
	// OwnRetry set, one of them replaces the default retry.
	Middlewares []string
	OwnRetry    bool
	// HealthPath makes Traefik probe each task too ("" = no check).
	HealthPath string
	// Path limits the route to a prefix ("" = the whole host); StripPrefix
	// removes it before forwarding. RedirectTo answers with a permanent
	// redirect to that host instead of forwarding (Phase 15c).
	Path        string
	StripPrefix bool
	RedirectTo  string
}

ServiceRoute is one public route to a service's tasks (§5.7).

type Settings

type Settings struct {
	// Static: entrypoints and proxy behaviour.
	LogLevel string `json:"logLevel"` // DEBUG | INFO | WARN | ERROR
	// Responding timeouts of the public entrypoints ("" = Traefik's default;
	// "0s" disables the limit).
	ReadTimeout  string `json:"readTimeout"`
	WriteTimeout string `json:"writeTimeout"`
	IdleTimeout  string `json:"idleTimeout"`
	// TrustedIPs are proxies (a CDN or a load balancer) whose
	// X-Forwarded-* headers are kept; from anyone else they are replaced.
	TrustedIPs []string `json:"trustedIPs"`
	// ProxyProtocol accepts the PROXY protocol from TrustedIPs, for load
	// balancers that pass the client address that way.
	ProxyProtocol bool `json:"proxyProtocol"`
	// HTTP3 serves HTTP/3 (QUIC) on the HTTPS port as well.
	HTTP3 bool `json:"http3"`
	// Upstream connections to tasks.
	DialTimeout           string `json:"dialTimeout"`
	ResponseHeaderTimeout string `json:"responseHeaderTimeout"`
	MaxIdleConnsPerHost   int    `json:"maxIdleConnsPerHost"`

	// Dynamic: defaults for every service route.
	RedirectHTTPS bool   `json:"redirectHttps"` // HTTP requests to service domains redirect to HTTPS
	MinTLS        string `json:"minTls"`        // "1.2" | "1.3"
	SNIStrict     bool   `json:"sniStrict"`     // refuse TLS clients without a known server name
	RetryAttempts int    `json:"retryAttempts"` // 0 disables the default retry
	HSTSSeconds   int    `json:"hstsSeconds"`   // 0 sends no Strict-Transport-Security
	Compress      bool   `json:"compress"`      // gzip/brotli/zstd responses
	MaxBodyMB     int    `json:"maxBodyMb"`     // request body limit, 0 = unlimited
}

Settings are the cluster-wide Traefik options (§5.7) for every replica, on the controller and on edge nodes. The static ones become command-line flags, so changing them restarts Traefik; the dynamic ones are part of the served configuration and apply within seconds.

func DefaultSettings

func DefaultSettings() Settings

DefaultSettings are what a fresh install uses.

func ParseSettings

func ParseSettings(text string) Settings

ParseSettings reads stored settings; missing fields keep their defaults.

func (Settings) StaticArgs

func (s Settings) StaticArgs() []string

StaticArgs are the command-line flags for every Traefik replica, added after the built-in ones.

func (*Settings) Validate

func (s *Settings) Validate() error

Validate checks every field and normalizes the trusted addresses.

type SourceCriterion

type SourceCriterion struct {
	IPStrategy struct {
		Depth int `json:"depth"`
	} `json:"ipStrategy"`
}

type StripPrefix

type StripPrefix struct {
	Prefixes []string `json:"prefixes"`
}

type TCPConfig

type TCPConfig struct {
	Routers           map[string]TCPRouter           `json:"routers"`
	Services          map[string]TCPService          `json:"services"`
	Middlewares       map[string]TCPMiddleware       `json:"middlewares,omitempty"`
	ServersTransports map[string]TCPServersTransport `json:"serversTransports,omitempty"`
}

TCPConfig carries the public database endpoints (Phase 12e): TLS is terminated by Traefik and routed by SNI.

type TCPIPAllowList

type TCPIPAllowList struct {
	SourceRange []string `json:"sourceRange"`
}

type TCPLoadBalancer

type TCPLoadBalancer struct {
	Servers          []TCPServer `json:"servers"`
	ServersTransport string      `json:"serversTransport,omitempty"`
}

type TCPMiddleware

type TCPMiddleware struct {
	IPAllowList *TCPIPAllowList `json:"ipAllowList,omitempty"`
}

type TCPRoute

type TCPRoute struct {
	// Host picks the route by SNI; empty takes any TLS connection on the
	// entrypoint (a dedicated port).
	Name, Entrypoint, Host string
	Servers                []string // host:port
	Allow                  []string // client CIDRs (empty: anyone)
	Plain                  bool     // no TLS: any plain connection on the entrypoint
	// Passthrough forwards the TLS connection undecrypted (the server
	// terminates it); ProxyProtocol sends the client's address first.
	Passthrough, ProxyProtocol bool
}

TCPRoute is one public TLS endpoint (a database's), or with Plain a public TCP port of a service passed through as is (Phase 15c).

type TCPRouter

type TCPRouter struct {
	Rule        string     `json:"rule"`
	EntryPoints []string   `json:"entryPoints"`
	Middlewares []string   `json:"middlewares,omitempty"`
	Service     string     `json:"service"`
	TLS         *RouterTLS `json:"tls,omitempty"`
}

type TCPServer

type TCPServer struct {
	Address string `json:"address"`
}

type TCPServersTransport added in v0.2.2

type TCPServersTransport struct {
	ProxyProtocol *ProxyProtocol `json:"proxyProtocol,omitempty"`
}

TCPServersTransport sets how Traefik connects to a TCP service's servers.

type TCPService

type TCPService struct {
	LoadBalancer TCPLoadBalancer `json:"loadBalancer"`
}

type TLSConfig

type TLSConfig struct {
	Certificates []Certificate         `json:"certificates,omitempty"`
	Options      map[string]TLSOptions `json:"options,omitempty"`
	Stores       map[string]TLSStore   `json:"stores,omitempty"`
}

type TLSOptions

type TLSOptions struct {
	MinVersion    string   `json:"minVersion"`
	SNIStrict     bool     `json:"sniStrict,omitempty"`
	ALPNProtocols []string `json:"alpnProtocols,omitempty"`
}

TLSOptions is Traefik's tls.options entry.

type TLSStore added in v0.1.2

type TLSStore struct {
	DefaultCertificate *Certificate `json:"defaultCertificate,omitempty"`
}

TLSStore sets the certificate for connections no other one matches, such as clients that send no SNI.

type UDPConfig

type UDPConfig struct {
	Routers  map[string]UDPRouter  `json:"routers"`
	Services map[string]UDPService `json:"services"`
}

UDPConfig carries public UDP ports of services (Phase 15c).

type UDPLoadBalancer

type UDPLoadBalancer struct {
	Servers []TCPServer `json:"servers"` // {address}
}

type UDPRoute

type UDPRoute struct {
	Name, Entrypoint string
	Servers          []string // host:port
}

UDPRoute is a public UDP port of a service.

type UDPRouter

type UDPRouter struct {
	EntryPoints []string `json:"entryPoints"`
	Service     string   `json:"service"`
}

type UDPService

type UDPService struct {
	LoadBalancer UDPLoadBalancer `json:"loadBalancer"`
}

Jump to

Keyboard shortcuts

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